Flask interview questions
Prepare for your Flask interview with these common questions and answers.
01What is Flask?
Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself.
02What is routing in Flask?
Routing in Flask is a mechanism to map URLs to a specific function that will handle the logic for that URL. The @app.route() decorator is used to bind a function to a URL. You can also define dynamic routes with variable parts.
03What is the purpose of the `request` object in Flask?
The request object contains all the data that is sent from the client to the server. This includes:
request.form: For form data (POST requests).request.args: For URL query parameters (GET requests).request.files: For uploaded files.request.method: The HTTP method of the request.request.json: For JSON data.
04What is a Flask Blueprint?
A Blueprint is a way to organize a group of related views and other code. Instead of registering views and other code directly with an application, they are registered with a blueprint. Then, the blueprint is registered with the application when it is available in a factory function. This helps in structuring larger applications.
05What is Jinja2?
Jinja2 is a modern and designer-friendly templating engine for Python, modeled after Django’s templates. It is used by Flask to render HTML templates. It allows you to write code in your templates, like loops, conditionals, and variable substitutions.
06How do you handle sessions in Flask?
Flask provides a session object that allows you to store information specific to a user from one request to the next. It is implemented on top of cookies and signs the cookies cryptographically. You need to set a secret_key on your application to use sessions.
07What is Flask-SQLAlchemy?
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. SQLAlchemy is a powerful Object-Relational Mapper (ORM) that gives application developers the full power and flexibility of SQL.
08What is the application context and request context in Flask?
Request Context: Keeps track of the request-level data during a request. The request and session objects are available in the request context.
Application Context: Keeps track of the application-level data. The current_app and g objects are available in the application context. It's used to find the application instance without passing it around.
09What is the `g` object in Flask?
The g object is a special object provided by Flask that is used for storing data during the lifetime of a single request. It's a place to store data that might be accessed by multiple functions during a request. For example, you could store a database connection on g.
10How do you handle errors in Flask?
You can use the @app.errorhandler(code) decorator to register a custom error handler function for a specific HTTP status code. This allows you to show custom error pages to the user.
11What is Flask-WTF?
Flask-WTF is an extension that integrates Flask with WTForms. WTForms is a flexible form validation and rendering library for Python. Flask-WTF provides features like secure forms with CSRF protection, file uploads, and reCAPTCHA support.
12What is CSRF protection and how does Flask handle it?
CSRF (Cross-Site Request Forgery) is an attack that tricks the victim into submitting a malicious request. Flask-WTF provides easy-to-use CSRF protection. It generates a unique token for each user session and requires this token to be sent with each state-changing request (like a POST request).
13How do you structure a large Flask application?
For large applications, it's common to use Blueprints to organize code into different modules. Another popular pattern is the Application Factory pattern, where you create a function that takes configuration and returns a Flask app instance. This helps with testing and managing different environments.
14What is the purpose of `url_for()`?
The url_for() function is used for URL building. It takes the name of the view function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. It's preferred over hard-coding URLs because it's more descriptive and handles URL escaping automatically.
15What are message flashing in Flask?
Message flashing is a system to record a message at the end of a request and access it on the next request. This is useful for providing feedback to the user, like 'Record was successfully saved'. You use the flash() function to flash a message and get_flashed_messages() in a template to display them.
16What is WSGI?
WSGI (Web Server Gateway Interface) is a specification that describes how a web server communicates with web applications. Flask is a WSGI-compliant framework. For production, you don't use Flask's built-in development server; instead, you use a production-ready WSGI server like Gunicorn or uWSGI.
17How can you configure a Flask application?
Configuration can be done in several ways:
- From a config object.
- From a Python file (
app.config.from_pyfile()). - From environment variables (
app.config.from_envvar()).
18What are Flask extensions?
Flask extensions are packages that add functionality to a Flask application that Flask itself doesn't provide. Examples include Flask-SQLAlchemy for database integration, Flask-Login for user authentication, and Flask-Migrate for database migrations.
19How do you test a Flask application?
Flask provides a test client that simulates requests to the application without running a live server. You can use a testing framework like pytest or Python's built-in unittest module to write tests for your views and application logic.
20What is the difference between `render_template` and `redirect`?
render_template() renders a Jinja2 template and returns it as an HTML response.
redirect() returns a response object that redirects the client to a different URL. It's often used with url_for().
21What is Flask-Login?
Flask-Login is an extension that provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering users' sessions over long periods of time. It does not handle user registration or password management.
22What is a decorator in the context of Flask?
In Flask, decorators are used extensively to add functionality to view functions. The most common is @app.route(), which registers a function as a request handler for a specific URL. You can also create custom decorators, for example, to require a user to be logged in.
23How do you handle file uploads in Flask?
File uploads are handled using the request.files object. You need to ensure your HTML form has enctype="multipart/form-data". In the view, you can access the uploaded file from request.files and save it to a secure location using its save() method.
24What is Flask-Migrate?
Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. It provides a set of commands to initialize a migration repository, generate new migrations, and apply them to the database.
25What is context processor in Flask?
A context processor is a function that runs before a template is rendered and has the ability to inject new values into the template context. It's useful for making certain variables (like a user object) available in all templates without passing them in every render_template call.
26What is Flask-RESTful?
Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs. It's a lightweight abstraction that works with your existing ORM/libraries. It encourages best practices with minimal setup.
27How do you stream content in Flask?
Flask can stream content by returning a Response object with a generator function. This is useful for sending large amounts of data (like a large CSV file) without having to load it all into memory at once.
28What is the purpose of the `__init__.py` file in a Flask project?
The __init__.py file serves two purposes: it tells Python that the directory should be treated as a package, and it's often where the application factory function is defined and where blueprints and extensions are initialized.
29What is a middleware in Flask?
A middleware is a function that wraps the WSGI application. It can be used to modify the request or response objects. Flask itself is a WSGI application, so you can wrap it with middleware for tasks like authentication, logging, or profiling.
30How can you make a Flask API response in JSON format?
You can use the jsonify() function. It serializes a Python dictionary to a JSON string and returns a Response object with the application/json mimetype.
Preparing for a role?
Tell us what you’re aiming for. A mentor can help you close the gaps before the interview.