A Comprehensive Tutorial on Python Flask: Top 20 Methods

Flask is a popular web framework for building web applications in Python. Known for its simplicity and flexibility, Flask provides the tools needed to create web applications with ease. In this tutorial, we will explore the top 20 methods in Flask, covering everything from routing to templates and form handling.

Note: Before you begin, make sure you have Flask installed. You can install it using pip:

pip install Flask

1. Import Flask

To get started with Flask, you need to import it in your Python script:

from flask import Flask
app = Flask(__name__)

2. Define a Route

Routes in Flask define the URLs that your application will respond to. You can define a route using the @app.route() decorator:

@app.route('/')
def index():
    return 'Hello, World!'

3. Running the Flask Application

To run your Flask application, use the following code at the end of your script:

if __name__ == '__main__':
    app.run(debug=True)

You can then start your application by running the script:

python your_script.py

4. Dynamic Routing

You can define dynamic routes that accept parameters:

@app.route('/user/<username>')
def user_profile(username):
    return f'User: {username}'

5. HTTP Methods

Flask allows you to specify which HTTP methods a route should respond to. The default is GET.

@app.route('/submit', methods=['POST'])
def submit_form():
    # Handle form submission
    pass

6. Redirects

You can redirect users to another URL using redirect():

from flask import redirect, url_for

@app.route('/redirect')
def redirect_example():
    return redirect(url_for('index'))

7. URL Building

Use url_for() to build URLs for your routes:

@app.route('/profile')
def user_profile():
    return url_for('user_profile', username='john')

8. Static Files

Serve static files (e.g., CSS, JavaScript) using the static folder in your project directory:

url_for('static', filename='style.css')

9. Templates

Flask supports Jinja2 templates for rendering HTML:

from flask import render_template

@app.route('/template')
def render_template_example():
    return render_template('template.html', variable_name='Hello, World!')

10. Request Object

Access request data using the request object:

from flask import request

@app.route('/request')
def get_request_data():
    user_agent = request.headers.get('User-Agent')
    return f'User Agent: {user_agent}'

11. Cookies

Set and read cookies using the cookies attribute of the request and response objects:

from flask import request, make_response

@app.route('/set_cookie')
def set_cookie():
    resp = make_response('Cookie set!')
    resp.set_cookie('user', 'John')
    return resp

@app.route('/get_cookie')
def get_cookie():
    user = request.cookies.get('user')
    return f'Hello, {user}!'

12. Sessions

Flask supports sessions for storing user-specific data across requests:

from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'your_secret_key'

@app.route('/login')
def login():
    session['user_id'] = 1
    return 'Logged in'

@app.route('/profile')
def profile():
    if 'user_id' in session:
        return f'User ID: {session["user_id"]}'
    return 'Not logged in'

13. Redirect After Login

Redirect users to a specific page after login using redirect():

from flask import redirect, url_for, request

@app.route('/login', methods=['POST'])
def login():
    # Perform login logic
    return redirect(request.args.get('next') or url_for('index'))

14. Error Handling

Handle errors with custom error pages:

@app.errorhandler(404)
def not_found_error(error):
    return 'Not Found', 404

15. File Uploads

Handle file uploads with Flask's request object:

from flask import request

@app.route('/upload', methods=['POST'])
def upload_file():
    uploaded_file = request.files['file']
    if uploaded_file.filename != '':
        # Handle the uploaded file
        pass

16. JSON Responses

Return JSON responses from your routes:

from flask import jsonify

@app.route('/json')
def json_response():
    data = {'message': 'Hello, World!'}
    return jsonify(data)

17. Blueprint

Organize routes into blueprints for modularity:

from flask import Blueprint

bp = Blueprint('my_blueprint', __name__)

@bp.route('/my-route')
def my_route():
    return 'My Route'

app.register_blueprint(bp)

18. Middleware

Use middleware functions to execute code before and after requests:

@app.before_request
def before_request():
    # Code to execute before each request
    pass

@app.after_request
def after_request(response):
    # Code to execute after each request
    return response

19. Custom Error Pages

Create custom error pages for different HTTP error codes:

@app.errorhandler(404)
def not_found_error(error):
    return 'Not

 Found', 404

20. Database Integration

Integrate a database with Flask using libraries like SQLAlchemy or Flask-SQLAlchemy for robust data handling.

With these top 20 methods, you can harness the power of Flask to create web applications that are dynamic, responsive, and feature-rich. Whether you're building a simple website or a complex web application, Flask's simplicity and versatility make it an excellent choice for web development in Python.