liminfo

Flask Reference

Free reference guide: Flask Reference

26 results

About Flask Reference

The Flask Reference is a comprehensive cheat sheet for Python web developers building web applications and APIs with the Flask microframework. It covers the six core areas of Flask development: URL routing with decorators and variable rules, request data access (args, form, JSON body, files, headers), response generation (jsonify, make_response, redirect, abort), Jinja2 template rendering with template inheritance and filters, Flask-SQLAlchemy ORM for database operations, and application configuration and error handling.

This reference is used by Python developers building REST APIs, server-side rendered web applications, and microservices. Flask's minimalist philosophy means you pick the components you need, so this reference reflects real-world patterns: using Blueprint to split a growing app into auth, admin, and API modules, using url_for() for reverse URL resolution, leveraging SQLAlchemy's query API with get_or_404(), and configuring the app from environment-specific config objects.

The reference is organized into six categories: Routing (@app.route with methods=[...], URL variable rules like <username> and <int:id>, url_for() reverse resolution, Blueprint modularization), Request (request.args GET params, request.form POST data, request.json body, request.files upload, request.headers), Response (jsonify() JSON output, make_response() for custom headers, redirect(), abort() HTTP errors), Templates (render_template with Jinja2 {{ }}, {% if %}/{% for %}, {% extends %} inheritance, | filter pipes), Database (Flask-SQLAlchemy db.Model, db.session CRUD, Model.query filtering), and Configuration (app.config, from_object(), @app.errorhandler, app.logger).

Key Features

  • @app.route decorator with methods=[] for GET, POST, PUT, DELETE method handling
  • URL variable rules — <username>, <int:id>, <path:subpath> type converters
  • Blueprint class for splitting large apps into auth, api, admin modules
  • request.args, request.form, request.json, request.files, request.headers access
  • jsonify() for JSON responses and make_response() for custom header injection
  • Jinja2 template inheritance with {% extends %}, {% block %}, and | filter pipes
  • Flask-SQLAlchemy db.Model definition, db.session CRUD, and query.get_or_404()
  • @app.errorhandler for custom 404/500 pages and app.logger for structured logging

Frequently Asked Questions

What is Flask and when should I use it instead of Django?

Flask is a lightweight WSGI microframework for Python that provides routing, request/response handling, and Jinja2 templating with minimal boilerplate. Choose Flask when you want full control over your stack, are building a REST API or microservice, or need to integrate specific libraries for ORM, auth, or serialization. Choose Django when you need batteries-included features like an admin interface, ORM migrations, and a user model out of the box.

How do I organize a large Flask application using Blueprints?

Create a Blueprint object in each module: bp = Blueprint("auth", __name__, url_prefix="/auth"). Define routes on the blueprint with @bp.route(). Register the blueprint on the app with app.register_blueprint(bp). Organize your project with one blueprint per domain area (auth, api, admin) each in its own package with routes.py, models.py, and forms.py. This keeps the main app factory small and each feature self-contained.

How do I access POST form data and JSON request body in Flask?

For HTML form submissions (Content-Type: application/x-www-form-urlencoded), read fields with request.form["fieldname"] or request.form.get("fieldname", default). For JSON APIs (Content-Type: application/json), read the parsed body with request.json or request.get_json(). For GET query parameters, use request.args.get("q"). For file uploads, access request.files["photo"] and call file.save() to write it to disk.

How does Flask-SQLAlchemy work for database operations?

Declare models by subclassing db.Model with db.Column fields. Create records with db.session.add(obj) followed by db.session.commit(). Query with Model.query.filter_by(active=True).all() for a list or Model.query.get_or_404(id) for a single record that automatically 404s if not found. For updates, fetch the object, modify its attributes, and call db.session.commit(). For deletions, call db.session.delete(obj) and commit.

How do I return JSON responses in Flask?

Use jsonify() to convert a Python dict or list to a JSON response with the correct Content-Type header: return jsonify({"status": "ok", "data": items}). To set a custom HTTP status code, chain it: return jsonify({"id": new_id}), 201. For full response control, use make_response() to get a response object, modify its headers, and return it. Flask 2.2+ also supports returning a plain dict directly without jsonify().

How do Jinja2 templates work in Flask?

Flask uses Jinja2 as its default template engine. Store templates in a templates/ folder. Render with render_template("page.html", title="Home", posts=posts). In templates, output variables with {{ variable }}, use logic with {% if condition %}...{% endif %} and {% for item in items %}...{% endfor %}. For shared layouts, create base.html with {% block content %}{% endblock %} and extend it with {% extends "base.html" %} in child templates. Apply filters with {{ name|upper }} or {{ text|truncate(100) }}.

How do I handle 404 and 500 errors in Flask?

Use the @app.errorhandler(code) decorator. For 404: @app.errorhandler(404) def not_found(e): return render_template("404.html"), 404. For 500: @app.errorhandler(500) def server_error(e): return jsonify({"error": "Internal server error"}), 500. To trigger errors manually in route handlers, call abort(404) or abort(403). You can also raise HTTPException subclasses directly for more control over the response body.

How do I manage Flask application configuration for different environments?

Define a base Config class with common settings and subclasses like DevelopmentConfig and ProductionConfig with environment-specific values (DEBUG, SQLALCHEMY_DATABASE_URI, SECRET_KEY). Load the correct config in the app factory with app.config.from_object(os.environ.get("APP_CONFIG", "config.DevelopmentConfig")). Keep secrets out of version control by reading them from environment variables with os.environ.get("SECRET_KEY") inside the config class.