Flask
Flask is a lightweight WSGI web framework. You decorate functions with routes, return strings or JSON, and add extensions for the rest. It stays out of your project layout until you invite it in.
Detailed Explanation
A Flask app is an Flask(__name__) instance. @app.get("/orders/<order_id>") binds a view. The function reads request (a context-local proxy), and returns a body, a status, and headers. jsonify or a dict (Flask 2.2+) becomes JSON. Templates use Jinja2. The development server is not a production server; use gunicorn or waitress in front of the WSGI app.
Application context and request context are thread-local (and greenlet-local) stacks. current_app and request work inside a request and raise outside one. Tests use app.test_client() and app.app_context(). Background jobs do not have a request; pass values in, do not read request later.
Flask is unopinionated about ORMs, forms, and auth. Flask-SQLAlchemy, Flask-Login, and Flask-WTF are common. That flexibility is why two Flask apps look nothing alike. Pick a structure (app package, blueprints per area) and keep it.
Blueprints split routes. An application factory create_app(config) is the usual pattern so tests can make an app without importing a global. Configuration from environment variables belongs in that factory.
Flask 2 added async views. An async def view still runs on WSGI via an event loop per request unless you deploy on an ASGI adapter. For many concurrent sockets, FastAPI or Quart is a better default. Flask remains excellent for small HTTP APIs and HTML apps.
Do not run the debugger in production. Do not use a secret key that is in the repo. Do set SESSION_COOKIE_SECURE behind HTTPS.
Code Examples
from flask import Flask, abort, jsonify
app = Flask(__name__)
ORDERS = {"11": {"cents": 2500}}
@app.get("/orders/<order_id>")
def get_order(order_id: str):
order = ORDERS.get(order_id)
if order is None:
abort(404)
return jsonify(order)
# flask --app shop run
# or: app.test_client().get("/orders/11")def create_app() -> Flask:
app = Flask(__name__)
app.config.from_mapping(SECRET_KEY="dev")
return appCommon Gotchas
Using the Flask dev server in production
it is single-process and unhardened. Put gunicorn in front.
Reading `request` in a thread you started
the context is not there. Pass `request.get_json()` into the thread.
A global `app` imported by workers
prefer an application factory so tests and CLI can configure cleanly.
`abort(404)` raises
it is not a return. Code after it does not run.