{jsonbody.com}

Top 50 Flask Interview Questions & Answers

Practise 50 Flask interview questions on routing, app and request contexts, blueprints, REST APIs, JWT, SQLAlchemy, testing and Gunicorn deployment.

Flask Fundamentals

Q1. What is Flask?

Flask is a lightweight Python web framework built on Werkzeug and Jinja. It provides routing, request handling and templates, and leaves choices such as the database and auth to extensions.

Q2. Why is Flask called a microframework?

Micro means the core stays small, not that it only suits small apps. Flask does not include an ORM or form library, so you add only what your project needs.

Q3. How does Flask compare with Django and FastAPI?

Flask is minimal and flexible, Django includes an ORM, admin and auth out of the box, and FastAPI focuses on type-hinted, async-first APIs with automatic docs.

Q4. How do you define a route?

Use a decorator such as @app.route("/users/<int:id>"). Since Flask 2.0, shortcuts like @app.get and @app.post are available for single HTTP methods.

Q5. What are URL converters?

Converters validate and convert path values, such as <int:id>, <float:price>, <path:file>, <uuid:key> and the default string. A value that does not match returns a 404.

Q6. What does url_for do?

It builds a URL from the endpoint name and its arguments, so links do not break when a route path changes. It also handles escaping and blueprint prefixes.

Q7. How do you read data from a request?

Use request.args for query strings, request.form for form fields, request.get_json() for JSON bodies, request.files for uploads and request.headers for headers.

Q8. How do you return JSON?

Return a dictionary or list and Flask converts it to JSON automatically, or call jsonify(). You can also return a tuple such as (data, 201) to set the status code.

Q9. What is Jinja?

Jinja is Flask's template engine, offering variables, loops, conditions and template inheritance. Flask turns on auto-escaping for HTML templates, which helps prevent XSS.

Q10. What is the difference between redirect and abort?

redirect() sends the client to another URL with a 3xx response. abort(404) stops the request immediately with an HTTP error, which can be handled by a custom error handler.

Contexts & Request Lifecycle

Q11. What is the application context?

It tracks app-level data during a request or CLI command and makes current_app and g available. Outside a request, you can push it with with app.app_context():.

Q12. What is the request context?

It holds data for the current HTTP request and makes request and session available. Flask pushes it when a request starts and removes it when the request ends.

Q13. How does request work as a global in a multithreaded server?

request is a proxy that points to the data for the current context, using Python's contextvars. Each worker or coroutine therefore sees its own request.

Q14. What is flask.g used for?

g stores data for the current app context, such as the current user or a database connection. It does not persist between requests, unlike session.

Q15. What is current_app?

A proxy to the app handling the current context. It lets blueprints and helpers read config without importing the app object, which avoids circular imports.

Q16. What do before_request and after_request do?

before_request runs before the view and can return a response to stop further processing. after_request receives the response and can change it, for example by adding headers.

Q17. What is the difference between after_request and teardown_request?

after_request handlers can be skipped if an unhandled error occurs. teardown_request runs when the context ends even after an error, so it suits cleanup work.

Q18. How do you handle errors centrally?

Register handlers with @app.errorhandler(404) or for an exception class. APIs can use this to return one consistent JSON error format.

Q19. How do Flask sessions work?

By default, session data is stored in a cookie signed with SECRET_KEY. Signing prevents tampering, but the data is readable by the client, so never put secrets in it.

Q20. How do you manage configuration?

Use app.config, loading values from environment variables, objects or files. Keep secrets out of source code and use separate settings for development, testing and production.

Application Structure

Q21. What is a Blueprint?

A Blueprint groups related routes, templates and error handlers so they can be registered on an app, optionally under a url_prefix. It is the usual way to split a larger app into modules.

Q22. What is the application factory pattern?

A create_app() function builds and configures the app rather than creating it at import time. This allows different configs for tests and production and helps avoid circular imports.

Q23. What does init_app do in an extension?

It binds an extension to a specific app after the extension object has been created. This lets you create db = SQLAlchemy() globally and attach it within the factory.

Q24. What is a MethodView?

A class-based view with one method per HTTP verb, such as get and post. It keeps related REST logic together, and it is registered with add_url_rule and as_view.

Q25. How do you create a custom CLI command?

Use @app.cli.command() with a function, then run it through the flask command. Commands get an app context automatically, so they are useful for tasks such as seeding data.

Q26. What are Flask signals?

Signals, based on Blinker, notify subscribers about events such as request_started. They are for loosely coupled observing, and they should not be used to change the outcome of a request.

Q27. How do you handle file uploads safely?

Read files from request.files, set MAX_CONTENT_LENGTH, check allowed types and clean names with Werkzeug's secure_filename. Store uploads outside the code directory, ideally with generated names.

Q28. How do you stream a large response?

Return a generator wrapped in Response, with stream_with_context if it needs request. This sends data in chunks rather than building it all in memory.

Q29. Does Flask support async views?

Yes, since 2.0 with the flask[async] extra, but each async view runs in its own event loop in a separate thread and still occupies a WSGI worker. For heavily async apps, consider Quart or FastAPI.

Q30. How do you structure a large Flask project?

Use an app factory, one Blueprint per feature and separate modules for models, services and schemas. Keep views thin, with business logic in a service layer that is easy to test.

REST APIs, Data & Security

Q31. How do you use a database with Flask?

Flask-SQLAlchemy is the common choice for adding SQLAlchemy models and session management, with one session scoped per request. You can also use SQLAlchemy directly or another database client.

Q32. What is Flask-Migrate?

An Alembic-based extension that creates and applies database migrations through commands like flask db migrate and flask db upgrade. Generated migrations should be reviewed before running.

Q33. How do you solve the N+1 query problem?

Use eager loading such as SQLAlchemy's selectinload or joinedload, so related rows are fetched up front. Turning on query logging helps you spot the problem.

Q34. How do you validate API input?

Flask has no built-in schema validation, so libraries such as Marshmallow or Pydantic are commonly used. Reject invalid data with a 400 or 422 response and clear field errors.

Q35. How do you add JWT authentication?

Flask-JWT-Extended provides token creation, refresh tokens and a @jwt_required() decorator. Use short-lived access tokens and strong secrets, and always send tokens over HTTPS.

Q36. How do you handle CORS?

Use the Flask-CORS extension and allow only the origins you trust. Avoid a wildcard origin on authenticated APIs, and remember that CORS is enforced by browsers, not servers.

Q37. How do you protect forms from CSRF?

Flask-WTF adds CSRF tokens to forms and validates them. APIs that use cookie authentication need protection too, while APIs using bearer tokens in headers are generally not exposed to CSRF.

Q38. How do you prevent SQL injection?

Use the ORM or parameterized queries, such as text("SELECT * FROM users WHERE id = :id") with bound values. Never build SQL with string formatting from user input.

Q39. How do you add rate limiting?

Flask-Limiter can apply limits by IP or user, such as 5 per minute on a login route. Use a shared store like Redis when you run more than one worker.

Q40. How do you add caching?

Flask-Caching supports view and function caching with backends such as Redis. Cache only safe, repeatable data, and make sure user-specific responses are not shared between users.

Testing & Deployment

Q41. How do you test a Flask app?

Call app.test_client() to send requests without a real server, usually within pytest fixtures. An app factory lets tests use TESTING=True and a separate database.

Q42. How do you test code that needs a context?

Use with app.app_context(): or with app.test_request_context():, so that helpers such as current_app, url_for and request work during the test.

Q43. Why not use flask run in production?

It starts a development server that is not built for production security or load. Use a WSGI server such as Gunicorn or uWSGI, usually behind Nginx or another reverse proxy.

Q44. Why is debug mode dangerous in production?

The interactive Werkzeug debugger can allow arbitrary code to run on the server if exposed. It also reveals stack traces, so debug mode must stay off in production.

Q45. What is WSGI?

WSGI is the standard interface between Python web apps and servers. A Flask app is a WSGI callable, which is why servers like Gunicorn can run it directly.

Q46. How do you run background jobs?

Long tasks should go to a queue such as Celery or RQ with a broker like Redis, so the request returns quickly. The worker then runs the task separately, and can retry it if needed.

Q47. What does ProxyFix do?

Behind a reverse proxy, Flask sees the proxy's address and protocol. ProxyFix reads X-Forwarded-* headers, but you should only trust the number of proxies you actually use.

Q48. How many Gunicorn workers should you run?

A common starting point is (2 x CPU cores) + 1, then adjust by measuring. I/O-heavy apps may benefit from threaded or gevent workers.

Q49. What should go in production logging?

Log request IDs, errors and useful events through Python's logging module, written to stdout or a central system. Do not log passwords, tokens or other sensitive data.

Q50. What security settings should you check before launch?

Use a strong SECRET_KEY, HTTPS, SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY, a suitable SameSite value, upload limits and updated dependencies, with debug mode off.