Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 72 ยท Practice and Review

Interview Questions

39 common Flask interview questions with concise answers: WSGI, contexts, blueprints, sessions, security, testing, concurrency and deployment.

Flask interviews usually probe two things: whether you know how the framework works underneath (request flow, contexts, sessions), and whether you can make sound engineering decisions around it (structure, security, deployment). This page collects 39 questions that come up again and again, grouped by level, with short answers you can expand in your own words.

Try to answer each question out loud before you open it. If you cannot explain an idea in two or three sentences, follow the link to the lesson and review it. Three questions come with runnable editors, so you can see the behavior instead of just reading about it.

Tip: short and correct beats long and vague. Give the answer, add a tiny example, and mention a trade-off ("signed cookies are simple but readable by the client"). That last step is what interviewers remember.

Junior level

Basics

What is Flask, and what does "micro-framework" mean?

Flask is a Python web framework built on Werkzeug (the WSGI toolkit: routing, request and response objects) and Jinja (templates). "Micro" means the core is small and makes few decisions for you: there is no built-in database layer, form library or admin. You add what you need through extensions such as Flask-SQLAlchemy or Flask-Login. It does not mean Flask is only for small apps; it means you choose the architecture. See What Is Flask?.

What is WSGI, and why does it matter for Flask?

WSGI is the standard interface between Python web servers and applications: the server calls a callable with a dictionary (environ) describing the request and a start_response function, and the callable returns the response body. A Flask object is such a callable. That is why one Flask app runs unchanged under the development server, Gunicorn or uWSGI, and why test clients can call it without any network. WSGI is synchronous: one worker handles one request at a time.

How does Flask compare with Django and FastAPI?

Django is "batteries included": ORM, admin, auth, forms and migrations in one opinionated package. Flask gives you routing and templates and lets you pick the rest, which suits small services and teams that want control. FastAPI is built on ASGI with type-hint-driven validation and automatic OpenAPI docs, and shines for async-heavy JSON APIs. None is universally better: choose by project size, team experience and whether you need async or an admin out of the box.

Why do we write Flask(__name__)?

The first argument is the import name of the application. Flask uses it to find the root folder, from which it locates the templates and static folders, and as the name of the app's logger. For a single module __name__ is the right value; in a package it is the package name. Passing a random string works for demos, but resource lookup may then fail. See Setup and Your First App.

How do routes and HTTP methods work? What do you get for free?

@app.route("/path", methods=[...]) (or @app.get, @app.post) maps a URL rule to a function. Without methods, a route accepts GET only. Flask automatically adds HEAD to GET routes and answers OPTIONS everywhere, and it returns 405 Method Not Allowed, with an Allow header, when the URL matches but the method does not. Dynamic parts such as <int:id> are converted before your function is called. See Routes and HTTP Methods.

Why use url_for instead of hard-coding URLs?

url_for("endpoint", **values) builds the URL from the route table, so changing a path in one decorator updates every link and redirect. It also URL-encodes values, adds the blueprint prefix, handles static files and can produce absolute URLs with _external=True. Hard-coded paths break silently when a route changes or the app is mounted under a prefix. See Building URLs with url_for.

What can a view function return?

A string (HTML, status 200), a dict or list (converted to JSON), a Response object, or a tuple such as (body, status), (body, status, headers) or (body, headers). A view may also return a redirect or call abort(). Returning None is an error. make_response gives you the response object when you need to set cookies or headers. See Responses, Status Codes and Headers.

How do you read query-string values, form fields and JSON bodies?

Through the request proxy: request.args for the query string, request.form for form-encoded bodies, request.files for uploads, request.get_json() for JSON, request.headers and request.cookies for the rest. Use .get() with defaults for optional values; indexing a missing key in request.form raises a 400 automatically. Everything from the client is untrusted and must be validated. See The Request Object.

What is Jinja autoescaping, and when is |safe dangerous?

Autoescaping converts <, >, & and quotes in template variables into HTML entities, so user text cannot inject markup or scripts (XSS). It is on for .html templates and render_template_string. The |safe filter (or Markup) turns it off for a value. Use it only for HTML you generated yourself or sanitized; never for user input. See Jinja Templates Basics.

What is the Post/Redirect/Get pattern?

After handling a successful POST, redirect the browser to a GET page instead of rendering a result directly. Then reloading does not resubmit the form, and the back button is safe. Pair it with flash() to show a success message on the next page. See Handling HTML Forms.

What is the difference between flask run and app.run(), and why is debug mode dangerous in production?

Both start Werkzeug's development server, which is single-purpose and not hardened. flask run discovers the app through --app or FLASK_APP and supports --debug for reloading. Debug mode exposes an interactive debugger that can execute arbitrary Python in the browser, so leaving it on in production is a remote-code-execution hole. Production uses a real WSGI server such as Gunicorn. See Project Layout and the flask Command.

Mid level

Contexts and structure

What are the application context and the request context? What is g?

The request context holds the current request and session and exists while a request is handled. The application context holds current_app and g and exists while the app is doing work, including CLI commands and background code that has no request. A request pushes both. g is a per-app-context scratch object for sharing data during one unit of work, for example a database connection. Accessing these proxies when no context is active raises RuntimeError. Try it:

Python Contexts, current_app and g

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each with block gets its own app context, so g.counter set in the first block is gone in the second. Contexts are built on Python's contextvars, which is why they are safe across threads and async tasks. See How a Request Flows Through Flask and Hooks, Application Context and g.

What is the application factory pattern, and why use it?

A function create_app(config=None) builds and returns a configured Flask object instead of creating one at import time. It lets tests create fresh apps with different configuration, allows several instances in one process, avoids circular imports, and pairs with the extension pattern (db = SQLAlchemy() at module level, db.init_app(app) inside the factory). See The Application Factory.

What is a blueprint? How do endpoint names change?

A blueprint is a reusable bundle of routes, error handlers, templates and static files that you register on the app, optionally under a url_prefix. It lets you split a large app by feature (auth, blog, api). Endpoint names become blueprint_name.function_name, so url_for("auth.login"), and a bare url_for(".login") is resolved relative to the current blueprint. A blueprint is not a mini-app: it has no config or lifecycle of its own. See Blueprints.

Name the request hooks and the order they run in.

before_request functions run before the view; if one returns a response, the view is skipped. after_request functions receive and return the response; they also see the 500 page Flask builds for an unhandled error, but are skipped if the exception is allowed to propagate (as in testing mode). teardown_request and teardown_appcontext are guaranteed to run at the end, even after errors, and are the place to release resources such as database connections. Watch the order:

Python Hook order, a short circuit and an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A hook that returns a response short-circuits the view but not the later hooks. For /boom, Flask turns the exception into a 500 response, which passes through after_request like any other response, and then tears down. See Hooks, Application Context and g.

How should configuration be managed across environments?

Keep defaults in code or a config object, override per environment with environment variables (app.config.from_prefixed_env()) or an instance-folder file, and never commit secrets. Use separate configurations for development, testing and production, selected in the factory. The twelve-factor rule applies: everything that varies between deploys comes from the environment. See Configuration and Environments.

What is the extension pattern (init_app)?

Extensions are created without an app (db = SQLAlchemy()) and bound later with db.init_app(app). This decouples them from one specific app object, so the same extension instance serves many app instances, which the factory pattern and tests need. Extensions keep per-app state in app.extensions, never in globals tied to a single app.

Sessions, errors and data

How do Flask sessions work, and are they secure?

By default the session is a dictionary serialized to JSON, signed with SECRET_KEY, and stored in a browser cookie. The signature stops the client from changing the data, but nothing hides it: the content is only encoded, so the client can read it. So never put secrets in the session, keep it small (cookies are limited to about 4 KB), and use a strong random key. Seeing it makes the point:

Python The session cookie is signed, not encrypted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The forged cookie is rejected because the signature no longer matches, and the server sees an empty session. For data that must stay private or can be large, use a server-side session store (such as Flask-Session) and keep only an id in the cookie. See Sessions.

What happens if the SECRET_KEY leaks, and how do you rotate it?

An attacker can forge valid session cookies for any user and any content, which is a complete authentication bypass for cookie-based login. Rotate by deploying a new key; all existing sessions become invalid and users log in again. Flask 3.1 supports SECRET_KEY_FALLBACKS, a list of old keys still accepted for verification, which allows rotation without logging everyone out.

How do you handle errors and customize error pages?

Use abort(404) to stop a request with an HTTP error, and register handlers with @app.errorhandler(404) (or by exception class) that return a response and the status code. Handlers can decide by request.path or Accept header whether to return HTML or JSON. Unhandled exceptions become a 500; in production log them and show a generic page, never a traceback. See Error Handling and Custom Error Pages.

How do you work with a database in Flask?

Either use the standard library (sqlite3 with a connection stored on g and closed in teardown_appcontext) or Flask-SQLAlchemy, which provides db.Model, a request-scoped session and helpers such as db.get_or_404. Always use parameterized queries or the ORM, never string formatting. Use migrations (Flask-Migrate/Alembic) to evolve the schema. See Using sqlite3 with Flask and Flask-SQLAlchemy Models.

What is the N+1 query problem and how do you avoid it?

Loading N parent rows and then touching a lazy relationship on each triggers one extra query per parent: N+1 queries in total. Avoid it by eager loading: selectinload (a second query using IN), joinedload (a JOIN) or a hand-written join. Check the real number of statements in tests or logs. See Relationships.

How do you test a Flask app?

Create the app through the factory with a testing config and an in-memory or temporary database, then use app.test_client() to send requests and assert on status codes, JSON and redirects. Use test_request_context() for code that needs a request but not a full cycle, and test_cli_runner() for CLI commands. Fixtures in pytest give each test a fresh app. See Testing Flask Apps with pytest.

What is the difference between PUT, PATCH, POST and DELETE in an API, and what is idempotency?

POST creates a resource or triggers an action and is not idempotent: repeating it can create duplicates. PUT replaces a resource and DELETE removes it; both are idempotent, so repeating them leaves the same final state. PATCH applies a partial change and may or may not be idempotent. Idempotency matters for retries, since a client can safely repeat a PUT after a timeout. See Designing a REST API.

Senior level

Security

How do you protect a Flask app against CSRF, XSS and SQL injection?

CSRF: include a per-session token in every state-changing form and verify it (Flask-WTF's CSRFProtect does this), plus SameSite=Lax cookies. XSS: keep Jinja autoescaping on, avoid |safe on user data, and set a Content-Security-Policy. SQL injection: parameterized queries or the ORM only. Add HttpOnly and Secure cookie flags and HTTPS-only deployment. See Web Security Essentials.

What is an open redirect, and how would you prevent one after login?

If the app redirects to a user-supplied next parameter, an attacker can craft /login?next=https://evil.example, and the victim lands on a phishing page from a trusted domain. Accept only local paths: the value must start with a single / and not //, or be checked against an allow-list of hosts with urlsplit. See Project: Users and Login.

How do you store passwords?

Never in plain text or with a fast hash. Store the output of a slow, salted, adaptive function (scrypt, bcrypt, Argon2 or PBKDF2) via generate_password_hash and verify with check_password_hash. The salt is random per password and stored in the hash string. Use one generic login error message and rate-limit attempts. See Password Hashing.

How do you secure uploads?

Treat the file name, content type and size as untrusted: set MAX_CONTENT_LENGTH, clean names with secure_filename or generate your own, allow-list extensions and check the actual bytes, store files outside the static folder (or in object storage), and never execute or serve them with a guessed type. See File Uploads.

Concurrency and deployment

How does Flask handle concurrent requests?

Flask itself does not; the WSGI server does. Gunicorn starts several worker processes, optionally with threads in each, and every worker handles one request per thread at a time. Because workers are separate processes, module-level variables are not shared between them, so caches, counters and rate-limit data kept in Python memory will diverge. Put shared state in a database or Redis.

Why is global mutable state a problem in a Flask app?

Under a multi-process server each worker has its own copy, so changes are not visible to others and are lost on restart. Under threads, unsynchronized writes race. Request-specific data must live in g, request or session, which are context-local. Use module globals only for constants and configured objects created at startup.

How would you deploy a Flask app to production?

Run it with a production WSGI server (Gunicorn or uWSGI) behind a reverse proxy such as nginx that terminates TLS, serves static files and buffers slow clients. Configure ProxyFix so Flask trusts the proxy's X-Forwarded-* headers and sees the right scheme, host and client address. Load configuration and secrets from the environment, run database migrations as a deploy step, provide a health-check route and ship logs to a central place. A common worker count is about twice the CPU cores plus one, adjusted by measurement. See Deployment.

Can Flask views be async? What are the limits?

Yes, with the async extra installed (pip install "flask[async]"), a view can be async def. Flask runs each coroutine on an event loop in the worker's thread, so the worker is still occupied for the duration of the request. You gain the ability to await several I/O calls concurrently inside one request, not the high connection counts of a fully ASGI framework. Context variables such as request work, but background tasks created inside the view do not outlive the request. See Async Views and Background Work.

How do you run work in the background?

Do not start bare threads inside request handlers: they die with the worker and have no retries or visibility. Push a job onto a queue (Celery, RQ or a similar system backed by Redis or a broker), run separate worker processes, and have the view return quickly with a job id the client can poll. Jobs must be idempotent because they may run twice. See Async Views and Background Work.

What caching options do you have?

At the HTTP level: Cache-Control, ETag and conditional requests (304 Not Modified), plus a CDN for static and public pages. At the application level: Flask-Caching with Redis or memcached for expensive queries and fragments, with explicit invalidation. Never cache pages that contain per-user data without keying the cache on the user. And fix slow queries before caching them. See Performance and Caching.

Design

Walk through what happens from the moment a request reaches Flask to the response.

The WSGI server calls the app with environ. Flask builds a Request and pushes the app and request contexts, opens the session, then runs before_request hooks. The URL map matches the path and method to an endpoint (404 or 405 if none). The view runs with the converted URL arguments, and its return value becomes a Response. after_request hooks run, the session is saved into a Set-Cookie header, the response is returned to the server, and the teardown functions run as the contexts pop. Errors anywhere are routed to error handlers.

flowchart LR
    A["WSGI server"] --> B["Push contexts,<br/>open session"]
    B --> C["before_request"]
    C --> D["URL match<br/>and view"]
    D --> E["Make response"]
    E --> F["after_request,<br/>save session"]
    F --> G["Teardown,<br/>pop contexts"]
    G --> H["Response to client"]

Hooks wrap the view; teardown always runs last.

How are request, g and current_app "global" yet thread-safe?

They are proxies (werkzeug LocalProxy objects) that look up the real object in a context variable every time you touch them. Because context variables hold a separate value per thread or async task, two concurrent requests each see their own request. Outside a context the lookup fails with RuntimeError. The consequence: do not store these proxies for later use in another thread; read the data you need, or pass the real object with current_app._get_current_object().

How would you design a medium-sized Flask project?

Use an application factory, split features into blueprints, keep extensions in one module, put business logic in plain functions or service classes that do not import request, and keep views thin. Models and queries live in their own layer, configuration comes from the environment, and tests build the app through the factory. This keeps code testable without HTTP. See Project Layout and Project: A Blog.

How do you change a database schema without downtime?

Use the expand/contract approach in several deploys: first add the new nullable column or table (compatible with the old code), deploy code that writes to both and reads the new one, backfill old rows in batches, then remove the old column in a later migration. Never rename or drop a column in the same release that stops using it, because old and new app versions run side by side during a rolling deploy. See Migrations with Flask-Migrate.

How would you add observability to a Flask service?

Configure structured logging (app.logger plus a formatter that includes a request id from g), log unhandled exceptions with stack traces to a collector or error tracker, expose a cheap /health endpoint for load balancers, and record metrics such as request duration and status codes in an after_request hook. Never log passwords, tokens or full request bodies. See Logging and Debugging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Flask app runs under Gunicorn with four worker processes and keeps a visit counter in a module-level integer. What happens?

    Workers are separate processes with separate memory. Shared state belongs in a database or Redis.
  2. 2. What does the session cookie's signature protect against?

    The data is only encoded, so it can be read; the signature makes tampering detectable. Use HTTPS for eavesdropping and a CSRF token for CSRF.
  3. 3. Which hooks are guaranteed to run at the end of every request, even when the view fails?

    Teardown functions always run when the contexts pop, which is why they release resources. after_request is not guaranteed: it is skipped if the exception propagates, as in testing mode.
  4. 4. Why is a bare thread started inside a view a poor way to run background work?

    Use a queue and dedicated workers so jobs survive restarts, can retry, and can be observed.
  5. 5. How do you prevent an open redirect after login?

    A value that starts with a single / stays on your site. Absolute URLs and //host values are rejected.

Summary

  • Know the basics cold: WSGI, routing and methods, url_for, return values, the request object, autoescaping and Post/Redirect/Get.
  • Mid-level questions revolve around contexts and g, the factory and blueprints, request hooks, signed-cookie sessions, error handling, the database layer and testing.
  • Senior questions test security (CSRF, XSS, SQL injection, open redirects, password storage), process-level concurrency, deployment topology, background jobs, caching and migrations.
  • Answer briefly, add a small example and mention the trade-off.
  • Try the examples in this page until you can predict their output before running them.

Next: the Flask Cheat Sheet, a quick reference for the syntax you use every day.