Flask Cheatsheet
Setup
Use this Flask reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Installation
A working-developer Flask quick reference: routing, requests, JSON APIs, templates, blueprints, databases, and deployment — dense, copy-paste-ready, current APIs.
pip install flask pip install "flask[async]" # async/await support pip install flask gunicorn # production WSGI
Minimal working app:
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello, World!" if __name__ == "__main__": app.run(debug=True)
Run without the if __name__ guard:
flask --app app run --debug
flask --app mypackage:create_app run # factory functionApplication Factory Pattern
Preferred for testing and blueprints. Returns a new Flask instance each call.
# myapp/__init__.py from flask import Flask from .extensions import db, login_manager from .blueprints.auth import auth_bp def create_app(config_object="myapp.config.DevelopmentConfig"): app = Flask(__name__, instance_relative_config=True) app.config.from_object(config_object) app.config.from_pyfile("config.py", silent=True) # instance/ override db.init_app(app) login_manager.init_app(app) app.register_blueprint(auth_bp, url_prefix="/auth") return app
flask --app "myapp:create_app" run --debugConfiguration
Built-in Config Keys
| Key | Default | Purpose |
|---|---|---|
SECRET_KEY | None | Signs cookies/sessions — required in production |
DEBUG | False | Reloader + debugger; never True in prod |
TESTING | False | Propagates exceptions; disables error catching |
SERVER_NAME | None | Host:port for URL generation outside request context |
APPLICATION_ROOT | "/" | URL prefix when app is mounted at sub-path |
MAX_CONTENT_LENGTH | None | Max request body size in bytes |
SEND_FILE_MAX_AGE_DEFAULT | None | Cache-Control max-age for static files |
TEMPLATES_AUTO_RELOAD | None | Reload templates on change (defaults to DEBUG) |
SESSION_COOKIE_NAME | "session" | Cookie name |
SESSION_COOKIE_HTTPONLY | True | JS cannot read session cookie |
SESSION_COOKIE_SECURE | False | HTTPS-only cookie |
SESSION_COOKIE_SAMESITE | None | "Lax", "Strict", or "None" |
PERMANENT_SESSION_LIFETIME | 31 days | timedelta for permanent sessions |
Removed keys to avoid in older snippets: ENV and FLASK_ENV (removed in Flask 2.3 — use --debug/FLASK_DEBUG), and the JSON keys JSON_SORT_KEYS / JSONIFY_PRETTYPRINT_REGULAR / JSONIFY_MIMETYPE (removed in Flask 2.3 — configure app.json instead, see the JSON APIs page).
Loading Config
# 1. From object / string app.config.from_object("myapp.config.ProductionConfig") # 2. From a Python file (relative to instance path) app.config.from_pyfile("config.py", silent=True) # 3. From environment variable pointing to a file app.config.from_envvar("APP_SETTINGS") # 4. From mapping / dict app.config.from_mapping({"SECRET_KEY": "dev", "DATABASE": "app.db"}) # 5. Direct assignment app.config["SECRET_KEY"] = "supersecret" # 6. From prefixed environment variables (FLASK_SECRET_KEY, ...) app.config.from_prefixed_env()
Config class pattern:
class Config: SECRET_KEY = "change-me" SQLALCHEMY_TRACK_MODIFICATIONS = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = "sqlite:///dev.db" class ProductionConfig(Config): DEBUG = False SQLALCHEMY_DATABASE_URI = "postgresql://user:pw@host/db"
Environment Variables
FLASK_APP=app.py FLASK_DEBUG=1 # FLASK_ENV was removed in Flask 2.3 SECRET_KEY=mysupersecret
Use python-dotenv to load .env automatically:
pip install python-dotenv
Flask auto-loads .flaskenv (public defaults) and .env (secrets) if python-dotenv is installed.
Development Server Options
flask run --host=0.0.0.0 # listen on all interfaces flask run --port=8080 flask run --debug # hot reload + debugger flask run --no-reload # disable hot reload only flask run --cert=adhoc # HTTPS with self-signed cert (pip install pyOpenSSL) flask run --cert=cert.pem --key=key.pem
app.run() kwargs (useful in scripts):
app.run( host="0.0.0.0", port=5000, debug=True, use_reloader=True, threaded=True, # handle requests in threads (default True) processes=1, )
Production Deployment
# Gunicorn (recommended) gunicorn "myapp:create_app()" -w 4 -b 0.0.0.0:8000 # uWSGI uwsgi --http :8000 --module myapp:app --processes 4 # Waitress (Windows-friendly) pip install waitress waitress-serve --port=8000 myapp:app
Never run Flask's built-in server in production — it is a development convenience (threaded by default, but not security-hardened, load-tested, or process-managed). Use a real WSGI server behind a reverse proxy.
Project Layout (Recommended)
myapp/ __init__.py # create_app() config.py extensions.py # db = SQLAlchemy(), etc. models/ blueprints/ auth.py api.py templates/ static/ instance/ config.py # secrets (gitignored) tests/ conftest.py .flaskenv