Flask
Flask cheat sheet covering routes, templates, blueprints, request handling, and REST API patterns with Python code examples.
Other Python Sheets
Setup & Basics
Initialize and configure Flask applications
Create and configure Flask app
# Quick Reference
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True)Routing
Define routes and handle HTTP methods
Define and organize routes
# 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()Request & Response
Handle request data and send responses
Work with request and response objects
# 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)Blueprints
Organize application with blueprints
Structure large applications with blueprints
# 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')Database Integration
Connect and work with databases using SQLAlchemy
Integrate Flask with SQLAlchemy ORM
# 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)Authentication
Implement user authentication and sessions
User login and session management
# 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('/')Error Handling
Handle errors gracefully
Catch and handle application errors
# 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)}), 500Middleware & Hooks
Process requests with middleware and hooks
Execute code before and after requests
# 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 responseTesting
Test Flask applications
Write tests for Flask applications
# 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 == 200Deployment
Deploy Flask applications to production
Deploy Flask apps with WSGI servers
# 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"]