Flask interview cheat sheet
WSGI, routing, contexts, blueprints, extensions, testing and deployment
Flask interviews check whether you understand what the micro-framework gives you and what you must add yourself. Expect questions on WSGI, the application factory, routing and url_for, the app and request contexts (g, current_app, request, session), blueprints, hooks and error handlers, the common extensions, testing and production deployment. The standard-library snippets rebuild small pieces of Flask so you can explain the internals. Read the 15-minute revision first, then use Quiz mode and answer out loud.
15-minute revision
- Flask is a micro-framework: a small core (routing, request/response, contexts, Jinja2 templates, signed-cookie sessions, CLI, test client) built on Werkzeug and Jinja2. The ORM, forms, auth and migrations come from extensions.
- Flask is a WSGI app. WSGI is one callable:
app(environ, start_response)that returns an iterable of bytes. Middleware is just a WSGI app that wraps another one. - Use an application factory (
create_app()) plus extensions created at module level and bound later withext.init_app(app). This avoids circular imports and lets tests build fresh apps. - Built-in URL converters:
string(default, no slash),int,float,path(allows slashes) anduuid. Build URLs withurl_for('endpoint', **values); extra values become the query string. - A view can return a
str, adictorlist(turned into JSON), aResponse, a generator (streaming) or a tuple(body, status)/(body, status, headers). - The app context exposes
current_appandg. The request context exposesrequestandsession. Flask pushes both for each request and pops them at the end. - Context locals are
contextvars+ WerkzeugLocalProxy.requestis one global name that points to the current request in each thread or coroutine. glives for one app context (normally one request). Use it for per-request data such as the DB connection or the current user, never for cross-request state.- The default
sessionis a signed, not encrypted cookie (itsdangerous HMAC withSECRET_KEY). Users can read it but cannot change it. Do not store secrets in it. - Jinja2 autoescapes templates ending in
.html,.htm,.xml,.xhtmland.svgwhen rendered withrender_template.|safeorMarkupturns escaping off for one value. - Blueprints group routes, templates, static files, hooks and error handlers. Endpoints become
blueprint_name.view_name, e.g.url_for('auth.login'). - Hook order:
before_request(in registration order; a non-None return skips the view) → view →after_request(reverse order, must return the response) →teardown_request/teardown_appcontext(always run, receive the exception). @app.errorhandler(404)or@app.errorhandler(SomeException)returns a custom response.abort(403)raises anHTTPException. Unhandled errors become a 500 unless debug mode propagates them.async defviews needpip install "flask[async]". Each request still holds one worker until it finishes; async only helps with concurrent I/O inside a request. Fully async apps should use Quart or FastAPI.- Test with
app.test_client()and pytest fixtures (app,client,runner). SetTESTING=Trueand use a separate database. - Production: Gunicorn (or uWSGI/Waitress) runs the WSGI app behind nginx. Never use
flask runin production. Wrap the app withProxyFixwhen behind a proxy.
Foundations
Micro-framework philosophy
Flask gives you a small, stable core and lets you choose every other piece.
- Micro means a small core, not a small app size. Flask does not pick your database, ORM, form library or auth system for you.
- The core is built on two Pallets libraries: Werkzeug (WSGI toolkit: request/response objects, routing, debugger, dev server) and Jinja2 (templates). It also uses itsdangerous (signing), Click (CLI) and Blinker (signals).
- Everything else comes from extensions that follow the
init_apppattern: Flask-SQLAlchemy, Flask-Migrate, Flask-Login, Flask-WTF, Flask-JWT-Extended, Flask-CORS and so on. - Flask is explicit: you create the app object, register routes with decorators and choose the project layout. There is no required folder structure beyond
templates/andstatic/. - Current line is Flask 3.1.x (requires Python 3.9+). Version 2.0 added
asyncviews and@app.get/@app.post; 2.3 removedbefore_first_requestandFLASK_ENV.
Interview questions
- What does "micro-framework" mean for Flask?
- What are Werkzeug and Jinja2, and how does Flask use them?
- When would you pick Flask over Django?
WSGI: the interface under Flask
A WSGI app is a callable app(environ, start_response) that returns an iterable of bytes; Flask is one.
- WSGI (PEP 3333) is the standard contract between Python web servers (Gunicorn, uWSGI, Waitress, mod_wsgi) and Python web apps.
- The server calls the app once per request with
environ(a dict of CGI-style keys:REQUEST_METHOD,PATH_INFO,QUERY_STRING,HTTP_*headers,wsgi.input) and astart_response(status, headers)callback. - The app calls
start_responseand returns an iterable of bytes, which lets the server stream the body. - Middleware is a WSGI app that wraps another WSGI app. It can change
environon the way in or headers on the way out.ProxyFixis an example. - A Flask object is callable:
Flask.__call__callsapp.wsgi_app(environ, start_response). Wrapapp.wsgi_app, notapp, so you keep the Flask object. - WSGI is synchronous: one request occupies one worker (process, thread or greenlet) until the response finishes. ASGI is the async successor used by FastAPI, Starlette, Quart and Django's async mode.
Interview questions
- What is WSGI and why does it exist?
- What is WSGI middleware? Give an example.
- WSGI vs ASGI?
App creation & the application factory
Build the app inside create_app() and bind extensions with init_app so you can make many configured instances.
Flask(__name__): the import name tells Flask the root path used to findtemplates/,static/and theinstance/folder.- An application factory is a function that creates, configures and returns the app. Register blueprints and extensions inside it.
- Create extensions at module level without an app (
db = SQLAlchemy()), then calldb.init_app(app)inside the factory. Extensions read the app throughcurrent_app. - Benefits: different configs per environment, a fresh app per test, several apps in one process, and no circular imports (blueprints import
dbfromextensions.py, not from the app). - The CLI finds a factory named
create_appormake_appautomatically:flask --app myproject run, or explicitlyflask --app "myproject:create_app('prod')" run. instance_relative_config=Truemakes config files load from theinstance/folder, which holds machine-specific secrets and is kept out of version control.
Interview questions
- What is the application factory pattern and why use it?
- How do extensions work with a factory if the app does not exist at import time?
- Why does Flask need
__name__when you create the app?
Routing, converters & url_for
Decorators map URL rules to view functions; converters type the variables; url_for builds URLs from endpoint names.
@app.route(rule, methods=[...])registers a rule. Shortcuts since 2.0:@app.get,@app.post,@app.put,@app.patch,@app.delete.- Variables use
<converter:name>:string(default, no/),int,float,path(allows/),uuid. A wrong type gives a 404, not a 500. - The endpoint defaults to the function name. With blueprints it is
blueprint.function.url_forworks with endpoints, so URLs can change without breaking links. url_for('user', user_id=7, tab='posts')gives/users/7?tab=posts. Add_external=Truefor an absolute URL and_anchorfor a fragment.- Trailing slash rule:
/projects/also serves/projectswith a redirect;/about(no slash) returns 404 for/about/. HEADis added automatically forGET, andOPTIONSis handled automatically. A method not listed returns 405 Method Not Allowed.- Custom converters subclass
werkzeug.routing.BaseConverter(setregex,to_python,to_url) and are registered inapp.url_map.converters.
Interview questions
- Why use
url_forinstead of hard-coding URLs? - What happens if a request hits
/users/abcfor the rule/users/<int:user_id>? - What is an endpoint in Flask?
- How do you serve a URL with a slash and without one?
Request & response objects
request gives parsed input (args, form, json, files, headers); views return values that Flask turns into a Response.
request.args= query string;request.form= form fields;request.files= uploads;request.values= args + form;request.cookies;request.headers.request.get_json()parses a JSON body. It fails with an error (415/400) when the content type or body is wrong;get_json(silent=True)returnsNoneinstead.- These are MultiDicts:
request.args.get('page', 1, type=int)converts safely;getlist('tag')returns all values for a repeated key. - Return values:
str→ HTML response;dictorlist→ JSON (jsonifyis called for you); tuple(body, status, headers); aResponse; or a generator for streaming. make_response()turns a value into aResponseso you can set cookies or headers.redirect(),abort()andsend_file()cover the other common cases.- Limit upload size with
MAX_CONTENT_LENGTH; larger requests get 413. Clean filenames withwerkzeug.utils.secure_filename.
Interview questions
- How do you read query params, form data, JSON and files in Flask?
- What can a Flask view return?
jsonifyvs returning a dict?
Contexts & state
App context vs request context & context locals
Flask pushes an app context (current_app, g) and a request context (request, session); proxies read them through contextvars.
- Application context:
current_appandg. It exists during a request and whenever you push it manually withapp.app_context()(CLI commands, scripts, tests). - Request context:
requestandsession. Pushing it also pushes an app context if one is not already active. - Both are pushed at the start of
wsgi_appand popped at the end. Teardown functions run just before they are popped. - The four names are proxies (
werkzeug.local.LocalProxy). Each attribute access looks up the current object in aContextVar, so each thread or coroutine sees its own request. gis a plain namespace on the app context: good forg.dborg.userduring one request. It is not shared between requests or workers.- Outside a context you get
RuntimeError: Working outside of application/request context. Fix it withwith app.app_context():orapp.test_request_context(). - Proxies do not cross threads. Pass plain data to a background thread, or use
current_app._get_current_object()to pass the real app object.
Interview questions
- Difference between the application context and the request context?
- How can
requestbe a global if many requests run at the same time? - What is
gand when would you use it? - You get "Working outside of application context" in a script. How do you fix it?
- Why might a background thread fail with a context error?
Sessions & SECRET_KEY
Flask's default session is a signed cookie: the client stores the data, SECRET_KEY proves it was not changed.
sessionworks like a dict. Flask serialises it to JSON, signs it with itsdangerous usingSECRET_KEY, and sends it as thesessioncookie.- Signed, not encrypted: anyone can base64-decode and read it. Changing it breaks the signature, so Flask ignores the cookie and starts an empty session.
SECRET_KEYmust be long, random and secret (python -c 'import secrets; print(secrets.token_hex())'). If it leaks, attackers can forge any session.- Rotate keys with
SECRET_KEY_FALLBACKS(Flask 3.1+): old keys can still verify cookies while new cookies use the new key. session.permanent = TrueusesPERMANENT_SESSION_LIFETIME(default 31 days); otherwise it is a browser-session cookie. In-place changes to nested values needsession.modified = True.- Cookies are limited to about 4 KB, and you cannot revoke a cookie session on the server. For large data or forced logout, use server-side sessions (Flask-Session with Redis or a DB).
Interview questions
- How do Flask sessions work by default?
- Is the Flask session encrypted?
- What happens if
SECRET_KEYleaks? - How would you log out a user from all devices with cookie sessions?
Building the app
Templates: Jinja2 & autoescaping
render_template renders Jinja2 files from templates/ with HTML autoescaping on, which blocks most XSS.
render_template('page.html', **context)looks in the app's and blueprints'templates/folders.render_template_stringrenders a string.- Syntax:
{{ expr }}outputs,{% stmt %}controls (if,for,block,extends,include,macro),{# #}comments,|filtertransforms. - Template inheritance: a
base.htmldefines{% block %}s; children{% extends 'base.html' %}and override blocks.{{ super() }}keeps the parent content. - Autoescaping is on for
.html,.htm,.xml,.xhtmland.svgtemplates:<,>,&, quotes become entities.render_template_stringalways autoescapes. |safe,Markup(...)and{% autoescape false %}turn escaping off. Use them only for trusted HTML.- Available in every template:
config,request,session,g,url_for()andget_flashed_messages(). Add more with@app.context_processor.
Interview questions
- How does Flask protect templates from XSS?
- What is template inheritance?
- What is a context processor?
Blueprints
A blueprint is a recordable set of routes, hooks, templates and handlers that you register on an app, often with a URL prefix.
bp = Blueprint('auth', __name__, url_prefix='/auth', template_folder='templates')creates it;app.register_blueprint(bp)applies it.- A blueprint is not an app. It records operations and replays them when it is registered. Setup calls after registration are an error since Flask 2.3.
- Endpoints are namespaced:
url_for('auth.login'). Inside the same blueprint,url_for('.login')is a relative shortcut. - Blueprint hooks (
bp.before_request,bp.errorhandler) apply only to that blueprint's routes.bp.before_app_requestandbp.app_errorhandlerapply app-wide. - Blueprints can be nested (
parent.register_blueprint(child), Flask 2.0+), and one blueprint can be registered twice with differentnameandurl_prefix, for example API v1 and v2. - Typical split: one blueprint per feature (
auth,blog,api), each in its own package with views, forms and templates.
Interview questions
- What is a blueprint and why use one?
- Blueprint vs a separate Flask app?
- Why does
@bp.errorhandler(404)not catch unknown URLs?
Configuration
app.config is a dict subclass loaded from objects, files and environment variables; only UPPERCASE keys count.
app.configis aflask.Config(a dict). Built-in keys includeSECRET_KEY,DEBUG,TESTING,MAX_CONTENT_LENGTH,SERVER_NAMEand theSESSION_COOKIE_*group.- Loaders:
from_object(class or module),from_pyfile,from_file(path, load=json.load)(also TOML withtomllib),from_mapping, andfrom_prefixed_env(). - Only UPPERCASE names are loaded by
from_objectandfrom_pyfile, so helper variables do not leak in. from_prefixed_env()readsFLASK_*variables, drops the prefix and parses values as JSON when possible (FLASK_TESTING=true→True). Double underscore sets nested keys.- Pattern: a base config class, subclasses per environment, secrets from the environment or the
instance/folder. Load in order so later sources override earlier ones. - Debug mode:
flask run --debugorDEBUG=True.FLASK_ENVandapp.envwere removed in Flask 2.3.
Interview questions
- How do you manage config for dev, test and prod in Flask?
- Why are only uppercase keys loaded from a config object?
- What is the instance folder?
Error handlers & abort
Register handlers per status code or exception class; Flask picks the most specific one by walking the exception's class hierarchy.
abort(404)raises a WerkzeugHTTPException(NotFound). You can also raise these classes directly, e.g.raise Forbidden().@app.errorhandler(404)orapp.register_error_handler(404, fn)registers a handler. The handler returns a response, usually with the status code, e.g.return render_template('404.html'), 404.- Handlers can target any exception class, such as a custom
APIErrororValidationError. Flask uses the most specific handler in the class hierarchy (MRO). - A handler for
HTTPExceptioncatches all HTTP errors, which is handy for JSON APIs: returne.code,e.name,e.description. - Unhandled exceptions become 500 Internal Server Error. In debug mode (or with
PROPAGATE_EXCEPTIONS) they propagate so the debugger or test sees them. - Blueprint handlers take priority over app handlers for errors raised in that blueprint's views.
Interview questions
- How do you create a custom 404 page in Flask?
- How do you return JSON errors instead of HTML in a Flask API?
- If handlers exist for both
HTTPExceptionandNotFound, which runs for a 404?
Request hooks: before / after / teardown
before_request can short-circuit, after_request edits the response, teardown_* always cleans up.
before_request: runs before the view in registration order. Returning a non-None value stops the chain and becomes the response (used for auth checks, maintenance mode).after_request(response): runs in reverse order, must return a response object. Use it for headers, cookies or logging.teardown_request(exc)andteardown_appcontext(exc)always run when the context pops, even after an unhandled error. Use them to close connections; they must not raise.after_this_request(fn)registers an after-request function from inside a view, for one request only.url_value_preprocessorandurl_defaultslet you pull common URL parts (likelang_code) intogand add them back inurl_for.before_first_requestwas removed in Flask 2.3. Do one-time setup in the factory instead.
Interview questions
- Difference between
after_requestandteardown_request? - How do you stop a request early in
before_request? before_first_requestno longer exists. What do you use instead?
Extensions & APIs
Flask-SQLAlchemy & Flask-Migrate
Flask-SQLAlchemy ties a SQLAlchemy session to the app context; Flask-Migrate wraps Alembic as flask db commands.
db = SQLAlchemy()gives youdb.Model,db.sessionand helpers. The session is scoped to the app context and removed automatically at teardown.- Flask-SQLAlchemy 3.x prefers SQLAlchemy 2.0 style:
db.session.execute(db.select(User).filter_by(email=e)).scalar_one_or_none(). The oldUser.queryAPI still works but is legacy. - Helpers:
db.get_or_404(User, id),db.first_or_404(stmt),db.paginate(stmt, page=, per_page=). - Flask-Migrate wraps Alembic:
flask db init(once),flask db migrate -m 'msg'(autogenerate a script),flask db upgrade/downgrade. - Always review autogenerated migrations: Alembic cannot detect renames (it sees drop + add) and misses some type or constraint changes.
- Avoid N+1 queries with
selectinload/joinedloadon relationships.
Interview questions
- How does Flask-SQLAlchemy manage the DB session per request?
- What does Flask-Migrate do?
- How do you find and fix N+1 queries in a Flask/SQLAlchemy app?
Auth & cross-origin: Flask-Login, JWT-Extended, CORS
Flask-Login handles session-based login; Flask-JWT-Extended issues and checks JWTs; Flask-CORS adds CORS headers.
- Flask-Login:
LoginManager, a@login_manager.user_loaderthat loads a user by id,UserMixin,login_user(),logout_user(),@login_requiredand thecurrent_userproxy. It stores the user id in the session. - Flask-JWT-Extended:
JWTManager(app),create_access_token(identity=...),create_refresh_token,@jwt_required(),get_jwt_identity(). Tokens can travel in headers or cookies (with CSRF protection). - Use short-lived access tokens plus refresh tokens. Revoke with a blocklist checked in
@jwt.token_in_blocklist_loader(Redis works well). - Keep the JWT
identitya string (e.g.str(user.id)): thesubclaim must be a string, and recent PyJWT versions check this. - Flask-CORS:
CORS(app, resources={r'/api/*': {'origins': [...]}}). CORS is enforced by browsers; it is not an auth mechanism. - Hash passwords with
werkzeug.security.generate_password_hash/check_password_hash(or argon2/bcrypt). Never store plain text.
Interview questions
- How does Flask-Login know who the current user is?
- When would you use JWTs instead of Flask sessions?
- How do you revoke a JWT before it expires?
- Your SPA gets a CORS error calling the Flask API. What do you check?
REST APIs with Flask & marshmallow
Use JSON views or MethodView classes, validate input with a schema library, and return consistent status codes and errors.
- Plain views returning dicts are enough for small APIs.
flask.views.MethodViewmaps HTTP methods toget,post,put,deletemethods on one class. - marshmallow schemas validate and deserialise input (
schema.load) and serialise output (schema.dump).loadraisesValidationErrorwith a dict of field messages. - flask-marshmallow adds Flask integration; with marshmallow-sqlalchemy you get
SQLAlchemyAutoSchemabuilt from models. Pydantic is a popular alternative. - Higher-level options: flask-smorest (marshmallow + OpenAPI docs), APIFlask, Flask-RESTX. Flask core has no built-in OpenAPI.
- REST basics: nouns in URLs (
/api/items/42), correct verbs,201+Locationon create,204on delete,400/422for invalid input,404,409for conflicts. - Version the API with a URL prefix (
/api/v1) via blueprints, and paginate list endpoints.
Interview questions
- How would you build a REST API in Flask?
- What is the difference between
schema.loadandschema.dumpin marshmallow? ViewvsMethodView?
Async views: support & limits
Flask 2.0+ runs async def views in an event loop per request, but the WSGI worker stays busy, so it does not raise throughput.
- Install
flask[async](adds asgiref). Then views, error handlers and before/after/teardown hooks can beasync def. - For each async view Flask starts an event loop in a thread (via asgiref's
async_to_sync), runs the coroutine to completion and returns. One request still holds one worker. - The benefit is concurrency inside a request: e.g.
asyncio.gatherof several HTTP calls. It does not let one worker serve more requests. - You cannot start background tasks with
asyncio.create_task; they are cancelled when the view finishes. Use Celery, RQ or another task queue. - Many extensions are sync-only; their decorators may not await async views. Extension authors use
current_app.ensure_sync(func). - For WebSockets, many long connections or an async-first codebase, use Quart (Flask API on ASGI) or FastAPI. Another option is running Flask under gevent workers.
Interview questions
- Does making Flask views
asyncmake the app handle more requests? - Why can't you use
asyncio.create_taskfor background work in a Flask view? - Flask async vs Quart vs FastAPI?
Testing, production & comparison
Testing with pytest & the test client
Create the app per test with a fixture, then drive it with app.test_client() and app.test_cli_runner().
app.test_client()sends requests without a server:client.get('/x', query_string=...),client.post('/x', json={...}). The response has.status_code,.get_json(),.data,.headers.- Standard fixtures in
conftest.py:app(factory with test config and setup/teardown of the DB),client, andrunnerfor CLI commands. - Set
TESTING=Trueso exceptions propagate to the test instead of becoming 500 pages, and turn off CSRF for form tests (WTF_CSRF_ENABLED=False). - Use
with client.session_transaction() as sess:to set session values before a request, e.g. to fake a logged-in user. with client:keeps the request context after a call, so you can checkrequestorsession.app.test_request_context()lets you unit-test helpers that needrequest.- Use a separate test database (SQLite in memory or a disposable Postgres container), and wrap each test in a transaction or recreate tables.
Interview questions
- How do you test a Flask application?
- How do you test a route that requires login?
- Why set
TESTING=True?
Deployment: Gunicorn / uWSGI + nginx
Run Flask with a production WSGI server behind a reverse proxy; never with flask run.
- The dev server is single-process and not hardened. In production use Gunicorn (most common), uWSGI, Waitress (also on Windows) or mod_wsgi.
- Gunicorn uses a pre-fork model: a master process manages N workers. Start with workers ≈
2 × CPU + 1for sync workers and tune with load tests. - Worker types:
sync(default),gthread(threads per worker),gevent/eventlet(green threads for I/O-heavy apps). - nginx in front: TLS termination, static files, buffering slow clients, gzip, rate limiting, then
proxy_passto Gunicorn on a local port or Unix socket. - Behind a proxy, wrap the app with Werkzeug
ProxyFixsorequest.remote_addr, scheme and host come from the trustedX-Forwarded-*headers. Setx_for=1etc. to the number of proxies. - Also: run migrations as a deploy step, log to stdout, add a health endpoint, set
SECRET_KEYfrom the environment, and use containers or systemd to supervise the process.
Interview questions
- Why not use
flask runin production? - Why put nginx in front of Gunicorn?
- How many Gunicorn workers should you run?
- After deploying behind nginx,
url_for(..., _external=True)giveshttp://links and all client IPs are 127.0.0.1. Why?
Security: CSRF, cookies & headers
Flask gives escaping and signed cookies; you add CSRF protection, secure cookie flags, security headers and upload limits.
- CSRF: Flask core has no CSRF protection. Use Flask-WTF (
CSRFProtect(app)plus{{ csrf_token() }}in forms or anX-CSRFTokenheader for AJAX). - Cookies: set
SESSION_COOKIE_SECURE=True, keepHTTPONLY=True, and setSAMESITE='Lax'(blocks most cross-site POSTs). Apply the same toREMEMBER_COOKIE_*for Flask-Login. - XSS: rely on Jinja autoescaping, avoid
|safeon user data, and add a Content-Security-Policy (Flask-Talisman or anafter_requesthook). - Headers:
Strict-Transport-Security,X-Content-Type-Options: nosniff,X-Frame-Optionsor CSPframe-ancestorsagainst clickjacking. - Limit input:
MAX_CONTENT_LENGTH, and since 3.1MAX_FORM_MEMORY_SIZEandMAX_FORM_PARTS. Validate uploads and usesecure_filename. SetTRUSTED_HOSTSto reject unexpectedHostheaders. - SQL injection: use the ORM or bound parameters, never f-strings in SQL. Open redirects: validate
nextURLs before redirecting.
Interview questions
- Does Flask protect against CSRF out of the box?
- How do you secure Flask cookies?
- What are the main security risks of running Flask in debug mode?
- How do you prevent an open redirect with a
nextparameter after login?
Flask vs Django vs FastAPI
Flask is a minimal WSGI toolkit, Django is batteries-included, FastAPI is async-first with type-driven validation.
- Flask: small core, choose your own ORM, auth and validation. Great for small to medium apps, microservices, and when you want control.
- Django: ORM, migrations, admin, auth, forms and security middleware built in and integrated. Great for large CRUD or content apps and big teams.
- FastAPI: built on Starlette (ASGI) and Pydantic. Type hints drive validation, serialization and automatic OpenAPI docs. Great for async, I/O-heavy JSON APIs.
- Concurrency: Flask is WSGI (async views limited); Django supports both WSGI and ASGI with async views; FastAPI is ASGI-native.
- Raw speed rarely decides; the database, caching and architecture usually matter more. Pick by team skill, ecosystem and the shape of the app.
Interview questions
- Flask vs Django: which would you choose and why?
- Flask vs FastAPI for a new JSON API?
- Can Flask scale to large applications?