Python logoPythonv3.1INTERMEDIATE

Flask

Flask cheat sheet covering routes, templates, blueprints, request handling, and REST API patterns with Python code examples.

10 min read
flaskpythonbackendapiwebwsgi
Loading your progress

Setup & Basics

Initialize and configure Flask applications

Create and configure Flask app

python
# Quick Reference
from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True)
💡 Use environment variables for configuration
🔍 Flask(__name__) creates the application instance
⚡ debug=True enables auto-reload and detailed errors
setupconfiguration

Routing

Define routes and handle HTTP methods

Route Handling

Define and organize routes

python
# Quick Reference
@app.route('/users/<int:user_id>')
def get_user(user_id):
    return {'id': user_id}

@app.route('/posts', methods=['GET', 'POST'])
def posts():
    if request.method == 'POST':
        return create_post()
    return get_posts()
💡 Use variable rules like <int:id> for type conversion
🔍 get_or_404() automatically returns 404 if not found
⚡ Specify methods parameter to handle multiple HTTP verbs
routingendpoints

Request & Response

Handle request data and send responses

Work with request and response objects

python
# Quick Reference
from flask import request, jsonify, make_response

# Get request data
data = request.get_json()
param = request.args.get('param')
file = request.files['file']

# Send responses
return jsonify({'key': 'value'})
return make_response('Custom', 201)
💡 jsonify() automatically sets Content-Type to application/json
🔍 request.get_json() parses JSON request body
⚡ make_response() gives full control over response
requestresponse

Blueprints

Organize application with blueprints

Structure large applications with blueprints

python
# Quick Reference
from flask import Blueprint

api = Blueprint('api', __name__)

@api.route('/users')
def users():
    return jsonify(users_list)

app.register_blueprint(api, url_prefix='/api')
💡 Blueprints help organize code into modules
🔍 url_prefix applies to all blueprint routes
⚡ Each blueprint can have its own error handlers
blueprintsorganization

Database Integration

Connect and work with databases using SQLAlchemy

Integrate Flask with SQLAlchemy ORM

python
# Quick Reference
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
💡 Use Flask-Migrate for database migrations
🔍 SQLAlchemy provides powerful ORM capabilities
⚡ Use lazy loading for relationships to optimize queries
📌 Always use app context when working with db outside request
databasesqlalchemy

Authentication

Implement user authentication and sessions

User login and session management

python
# Quick Reference
from flask_login import LoginManager, login_user, logout_user

login_manager = LoginManager(app)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/login', methods=['POST'])
def login():
    user = authenticate_user()
    login_user(user)
    return redirect('/')
🔒 Always hash passwords with werkzeug.security
💡 Use Flask-Login for session management
🔍 JWT tokens for API authentication
⚡ @login_required decorator protects routes
authenticationsecurity

Error Handling

Handle errors gracefully

Error Handlers

Catch and handle application errors

python
# Quick Reference
@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Not found'}), 404

@app.errorhandler(Exception)
def handle_error(error):
    return jsonify({'error': str(error)}), 500
💡 Custom exceptions provide better error context
🔍 Log errors for debugging in production
⚡ Don't expose internal errors to users
📌 HTTPException covers all HTTP status codes
errorsexceptions

Middleware & Hooks

Process requests with middleware and hooks

Request Hooks

Execute code before and after requests

python
# Quick Reference
@app.before_request
def before():
    g.start_time = time.time()

@app.after_request
def after(response):
    response.headers['X-Time'] = time.time() - g.start_time
    return response
💡 Use g object to store request-scoped data
🔍 before_request can return early to abort request
⚡ after_request modifies all responses
📌 teardown runs even if exception occurs
middlewarehooks

Testing

Test Flask applications

Write tests for Flask applications

python
# Quick Reference
import pytest

@pytest.fixture
def client():
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

def test_home(client):
    rv = client.get('/')
    assert rv.status_code == 200
💡 Use pytest fixtures for test setup
🔍 Test with in-memory database for speed
⚡ test_client() provides request simulation
📌 Test both success and failure cases
testingpytest

Deployment

Deploy Flask applications to production

Deploy Flask apps with WSGI servers

python
# Quick Reference
# gunicorn
gunicorn app:app --workers 4 --bind 0.0.0.0:8000

# uwsgi
uwsgi --http :8000 --wsgi-file app.py --callable app

# Docker
FROM python:3.9
COPY . /app
RUN pip install -r requirements.txt
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000"]
💡 Use Gunicorn or uWSGI for production
🔍 Place Nginx in front for static files and SSL
⚡ Enable connection pooling for databases
📌 Set FLASK_ENV=production for security
deploymentproduction