Interview Q&A · questions with model answers

Flask Interview Questions

Ordered by how often they're asked. Most-asked answers are free to read in full; members see every answer and can rate their confidence on each.

  1. Most asked How do you access request data and build responses in Flask?

    Use the request proxy: request.args (query), request.form (form fields), request.get_json() (JSON body), request.files, request.headers, request.cookies. Return a string, dict (auto-JSON), tuple…

  2. Most asked How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?

    Create db = SQLAlchemy(model_class=Base) in an extensions module, call db.init_app(app) in the factory, define models with SQLAlchemy 2.0 typed Mapped columns, and query with…

  3. Most asked How do you implement user authentication in Flask?

    For session-based web apps use Flask-Login (user loader, login_user, logout_user, @login_required, current_user) with hashed passwords (Werkzeug's generate_password_hash or Argon2). For APIs use…

  4. Most asked How do you test a Flask application?

    Create the app via the factory with a testing config in a pytest fixture, use app.test_client() to make requests, app.test_cli_runner() for CLI commands, and set up an isolated database per test.

  5. Most asked How do you deploy a Flask app to production?

    Run it with a production WSGI server such as Gunicorn, uWSGI or Waitress (never the development server), behind a reverse proxy like Nginx that handles TLS, static files and buffering, typically in…

  6. Most asked How do you prevent SQL injection in Flask apps?

    Use SQLAlchemy's query building or bound parameters (text('... WHERE id = :id') with params) and never build SQL with f-strings from user input; allow-list identifiers like sort columns.

  7. How do you manage configuration in Flask?

    Configuration lives in app.config (a dict). Load it from Python objects (from_object), files (from_pyfile, from_file with TOML/JSON), environment variables (from_prefixed_env reads FLASK_*), and…

  8. How do you build a REST API in Flask with validation and serialization?

    Use blueprints for resources, validate request bodies with a schema library (marshmallow, Pydantic, or an integrated tool like flask-smorest or APIFlask that also generates OpenAPI docs), and return…

  9. How do you run background tasks in a Flask app?

    Use a task queue such as Celery (with Redis/RabbitMQ), RQ or Dramatiq. Configure it in the app factory so tasks run inside an app context, enqueue jobs from views, and run separate worker processes.

  10. How do you write a custom view decorator such as `@roles_required('admin')`?

    Write a decorator factory that returns a wrapper using functools.wraps(view); the wrapper checks the condition (e.g., current_user.role) and calls abort(403) or proceeds to the view.

  11. How do you secure a Flask JSON API with JWTs?

    Use Flask-JWT-Extended: issue tokens with create_access_token(identity=...), protect views with @jwt_required(), read the identity with get_jwt_identity(), and configure expiry, refresh tokens and a…

  12. How do you detect and fix N+1 queries in a Flask/SQLAlchemy app?

    Detect them by logging SQL (SQLALCHEMY_ECHO), using Flask-DebugToolbar or APM traces; fix them with eager loading (selectinload, joinedload) or explicit joins, and by selecting only needed columns.

  13. How do you add custom CLI commands to a Flask app?

    Use @app.cli.command() (or bp.cli.command()) with Click decorators; commands run inside an app context, so extensions and current_app work. Invoke them with flask <command>.

  14. How do you add caching to a Flask application?

    Use Flask-Caching with a Redis or Memcached backend to cache view output (@cache.cached(timeout=60)), function results (@cache.memoize), or arbitrary keys, plus HTTP caching headers for clients and…

  15. How do you enable CORS for a Flask API?

    Use Flask-CORS: CORS(app, origins=[...], supports_credentials=True) or per-blueprint/resource configuration, allowing only specific origins.

  16. How do you implement rate limiting in Flask?

    Use Flask-Limiter with a Redis storage backend, defining default limits and per-route limits (@limiter.limit('5/minute')) keyed by IP, user or API key.

  17. How do you stream a response in Flask?

    Return a generator wrapped in a Response (or just return the generator); use stream_with_context if the generator needs request or other context-bound objects while streaming.

  18. How do you write your own Flask extension?

    Create a class that can be instantiated without an app and implements init_app(app) to set config defaults, register hooks/teardown and store state in app.extensions['name']; access it later via…

  19. How would you implement social login in Flask?

    Use Authlib's Flask client (or Flask-Dance) to register providers (Google, GitHub), redirect to authorize_redirect, handle the callback with authorize_access_token, read user info/ID token claims,…

  20. How do you add real-time features (WebSockets) to Flask?

    Use Flask-SocketIO (Socket.IO protocol with eventlet/gevent or threading) or Flask-Sock for plain WebSockets; for multiple server processes, configure a message queue (Redis) so events reach all…

  21. How do you connect to multiple databases with Flask-SQLAlchemy?

    Configure SQLALCHEMY_BINDS = {'analytics': 'postgresql://...'} and set bind_key = 'analytics' on models (or bind_key on tables); queries for those models use the bound engine.

  22. How do you customize JSON serialization in Flask?

    Subclass flask.json.provider.DefaultJSONProvider (or set app.json to a custom provider) to handle types like Decimal, UUID or dataclasses, or to use a faster library like orjson.

  23. How do you internationalize a Flask app?

    Use Flask-Babel: mark strings with gettext/_() in code and templates, extract them with pybabel extract, translate .po files, compile to .mo, and select the locale per request with a locale selector…

  24. How do you send emails from Flask?

    Use Flask-Mail (or Flask-Mailman, or a provider SDK), render templates for bodies, and send asynchronously through a task queue so requests aren't slowed by SMTP latency.

  25. How do you implement pagination in Flask APIs?

    Read page/per_page (or cursor/limit) from request.args with defaults and caps, and use db.paginate(select, page=..., per_page=..., max_per_page=...) or keyset queries; return items with metadata and…

  26. How do you monitor a Flask app in production?

    Add error tracking (Sentry's Flask integration), metrics (prometheus-flask-exporter or OpenTelemetry metrics), distributed tracing (OpenTelemetry Flask/SQLAlchemy/requests instrumentation) and…

  27. How do you profile and speed up a slow Flask endpoint?

    Profile with Werkzeug's ProfilerMiddleware, py-spy or an APM, then fix the hotspots: usually database queries (N+1, indexes), repeated external calls (cache them), heavy serialization, or work that…

  28. How do you containerize a Flask app?

    Use a slim Python base image, install dependencies from a lock file, copy the app, run as a non-root user, and start Gunicorn (gunicorn -w 4 -b 0.0.0.0:8000 'myapp:create_app()'), with config from…

  29. How do you create a custom URL converter?

    Subclass werkzeug.routing.BaseConverter, set a regex, implement to_python and to_url, and register it in app.url_map.converters['name'].

  30. How would you version a Flask API?

    Register versioned blueprints with prefixes (/api/v1, /api/v2) that share underlying services, keep old versions until clients migrate, and document deprecations.

  31. How do you implement Server-Sent Events in Flask?

    Return a streaming Response with mimetype='text/event-stream' from a generator yielding data: ...\n\n messages, and use a worker type suited to long-lived connections (gevent/threads).

  32. How do you implement health checks for a Flask service?

    Add a lightweight /healthz route for liveness and a /readyz route that checks the database and critical dependencies with short timeouts, excluded from auth and rate limits.

  33. How do you mock external services when testing Flask apps?

    Inject service clients via the app factory or config so tests can substitute fakes, or patch them with unittest.mock.patch/pytest-mock; mock HTTP with responses (for requests) or respx (for httpx).

  34. How do you test login-protected Flask views?

    Log in through the test client (post to the login route), use a fixture that creates a user and session, or (for Flask-Login) set LOGIN_DISABLED or use client.session_transaction() to set the user…

  35. How do you tune database connection pooling for a Flask app?

    Configure SQLAlchemy engine options (pool_size, max_overflow, pool_pre_ping, pool_recycle) via SQLALCHEMY_ENGINE_OPTIONS, sized so workers × pool size stays under the database's connection limit.

  36. How would you add a GraphQL endpoint to Flask?

    Use a library like Strawberry (with its Flask view) or Graphene + graphql-server, define a schema with types and resolvers, and mount the view at /graphql.

  37. How do you run scheduled jobs in a Flask ecosystem?

    Use cron/systemd timers calling Flask CLI commands, Celery beat, RQ Scheduler, or APScheduler (carefully: with multiple workers, ensure only one scheduler runs).

  38. How do you render custom 404 and 500 pages in Flask?

    Register @app.errorhandler(404) and @app.errorhandler(500) handlers that return render_template('404.html'), 404; for blueprints serving APIs, return JSON instead based on the request path or Accept…

  39. How would you incrementally migrate a Flask app to FastAPI?

    Mount the Flask app inside FastAPI with WSGIMiddleware (or route by path at the proxy), build new endpoints in FastAPI, share the service and data layers, and move routes over gradually.

  40. How do you set, read and delete cookies in Flask?

    Read with request.cookies.get('name'); set with response.set_cookie('name', value, max_age=..., secure=True, httponly=True, samesite='Lax'); delete with response.delete_cookie('name').

  41. How can you generate signed, expiring tokens (e.g., password reset links) in Flask?

    Use ItsDangerous's URLSafeTimedSerializer(secret_key, salt='reset') to dumps a payload (user ID) and loads(token, max_age=3600) to verify it, catching SignatureExpired/BadSignature.

  42. How can you get automatic OpenAPI docs for a Flask API?

    Use frameworks built on Flask such as APIFlask, flask-smorest or flask-openapi3, which generate OpenAPI specs from schemas and decorators and serve Swagger UI/ReDoc.

  43. How would you implement multi-tenancy in Flask?

    Resolve the tenant per request (subdomain via subdomain routing, header, or user claim) in a before_request hook storing it on g, and scope all queries by tenant centrally (session events, base…

  44. How do you send CSRF tokens with AJAX requests in a Flask-WTF app?

    Expose the token with {{ csrf_token() }} in a meta tag, and have your JavaScript send it in the X-CSRFToken header on state-changing requests; CSRFProtect validates the header automatically.

  45. How do you let users download files in Flask?

    Use send_file() for a path or file-like object, or send_from_directory(directory, filename) for user-specified names (it prevents path traversal), with as_attachment=True and a download_name to…

  46. How do you use Redis in a Flask application?

    Create a redis.Redis.from_url(...) client (or use Flask-Redis) in the app factory, store it in app.extensions, and use it for caching, sessions, rate limiting, queues (RQ/Celery broker) and pub/sub.

  47. How should you generate and rotate Flask's `SECRET_KEY`?

    Generate it with a CSPRNG (python -c 'import secrets; print(secrets.token_hex(32))'), store it in a secrets manager or environment variable, and rotate it using SECRET_KEY_FALLBACKS (Flask 3.1+) so…

Was this page helpful?

Report a mistake