Python Flask Cheat Sheet

Installation

pip install Flask

Hello World

Let’s start with the classic “Hello, World!” example. Create a file named app.py and add the following code:

from flask import Flask

app = Flask(__name__)

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

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

Save the file and run it using:

python app.py

Visit http://127.0.0.1:5000/ in your web browser, and you should see “Hello, World!”

Routing

Flask uses routes to map URLs to functions. Here’s an example with multiple routes:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Home Page'

@app.route('/about')
def about():
    return 'About Page'

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

Visit http://127.0.0.1:5000/ and http://127.0.0.1:5000/about to see the different responses.

Dynamic Routing

You can capture dynamic values from the URL using angle brackets < >. Here’s an example:

from flask import Flask

app = Flask(__name__)

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

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

Access it via http://127.0.0.1:5000/user/johndoe.

Templates

Flask uses Jinja2 templates for rendering HTML. Create a folder named templates and add an HTML file, e.g., index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Template Example</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Now, modify the Flask app to render this template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/greet/<name>')
def greet(name):
    return render_template('index.html', name=name)

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

Visit http://127.0.0.1:5000/greet/John to see the personalized greeting.

Forms

Handling user input through forms is essential. Here’s a simple example

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        return f'Username: {username}, Password: {password}'
    return render_template('login.html')

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

Static Files

To serve static files (like CSS, JavaScript, or images), create a folder named static. Place your static files inside and use the url_for function in templates to generate URLs.

from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/static_example')
def static_example():
    return render_template('static_example.html')

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

Create a template (static_example.html) that includes a reference to a static file:

<!DOCTYPE html>
<html>
<head>
    <title>Static Example</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <h1>Static File Example</h1>
    <img src="{{ url_for('static', filename='image.jpg') }}" alt="Flask Logo">
</body>
</html>

Redirects and Errors

Handle redirects and errors in your application:

from flask import Flask, redirect, abort

app = Flask(__name__)

@app.route('/redirect_example')
def redirect_example():
    return redirect('https://www.example.com')

@app.route('/error_example')
def error_example():
    abort(404)  # Not Found

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

Cookies and Sessions

Utilize cookies and sessions for handling user data:

from flask import Flask, request, make_response, session

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

@app.route('/set_cookie/<value>')
def set_cookie(value):
    response = make_response(f'Cookie set to {value}')
    response.set_cookie('custom_cookie', value)
    return response

@app.route('/get_cookie')
def get_cookie():
    value = request.cookies.get('custom_cookie')
    return f'Cookie value: {value}'

@app.route('/set_session/<value>')
def set_session(value):
    session['custom_session'] = value
    return f'Session set to {value}'

@app.route('/get_session')
def get_session():
    value = session.get('custom_session')
    return f'Session value: {value}'

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

Remember to keep the secret_key secure in a real-world scenario.

Database Integration

Flask can easily integrate with databases. Here’s an example using SQLite:

from flask import Flask, render_template, g
import sqlite3

app = Flask(__name__)
app.config['DATABASE'] = 'example.db'

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(app.config['DATABASE'])
        g.db.row_factory = sqlite3.Row
    return g.db

@app.teardown_appcontext
def close_db(error):
    if 'db' in g:
        g.db.close()

@app.route('/database_example')
def database_example():
    db = get_db()
    cursor = db.execute('SELECT * FROM users')
    users = cursor.fetchall()
    return render_template('database_example.html', users=users)

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

Middleware

Middleware in Flask allows you to execute code before and after each request. Here’s an example using middleware for logging:

from flask import Flask, request

app = Flask(__name__)

@app.before_request
def before_request():
    app.logger.info(f'Before Request: {request.path}')

@app.after_request
def after_request(response):
    app.logger.info(f'After Request: {request.path}')
    return response

@app.route('/middleware_example')
def middleware_example():
    return 'Middleware Example'

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

In this example, the before_request function is called before each request, and the after_request function is called after each request.

File Uploads

Flask makes handling file uploads straightforward:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        file.save(f'uploads/{file.filename}')
        return 'File Uploaded Successfully'
    return render_template('upload.html')

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

Create a template (upload.html) with a form that allows file uploads.

<!DOCTYPE html>
<html>
<head>
    <title>File Upload Example</title>
</head>
<body>
    <h1>File Upload</h1>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept=".txt, .pdf, .jpg, .png" required>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

Blueprint

Blueprints help organize larger Flask applications. Here’s a simple example using blueprints:

from flask import Flask, Blueprint, render_template

main_bp = Blueprint('main', __name__)

@main_bp.route('/blueprint_example')
def blueprint_example():
    return render_template('blueprint_example.html')

app = Flask(__name__)
app.register_blueprint(main_bp)

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

Create a template (blueprint_example.html) for the blueprint.

<!DOCTYPE html>
<html>
<head>
    <title>Blueprint Example</title>
</head>
<body>
    <h1>Blueprint Example</h1>
</body>
</html>

RESTful API

Flask is excellent for building RESTful APIs. Here’s a simple example:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/greet/<name>', methods=['GET'])
def api_greet(name):
    return jsonify({'message': f'Hello, {name}!'})

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

Access the API at http://127.0.0.1:5000/api/greet/John.

Leave a Reply