Flask Interview Questions and Answers

Last Updated : 29 Jul, 2026

Flask is a lightweight Python web framework used to build web applications, REST APIs, and backend services. Preparing for a Flask interview requires a good understanding of routing, templates, request handling, databases, authentication, and application deployment.

1. What is Flask, and why is it widely used for Python web development?

  • Flask is a micro web framework in Python for building web applications.
  • It is based on WSGI (Web Server Gateway Interface) and uses the Jinja2 template engine.
  • Flask is flexible, easy to learn, and provides visual debugging for better control during development.

2. What is WSGI, and why does Flask use it?

  • WSGI (Web Server Gateway Interface) is a standard interface defined in PEP 3333 between web servers and Python web applications.
  • It specifies how a server passes an incoming HTTP request to an application and how the application returns a response back to the server.
  • Flask's own app object is itself a WSGI application — calling app(environ, start_response) is what actually happens under the hood every time a request comes in.
  • This is why Flask apps can be deployed behind Gunicorn or uWSGI in production without changing any application code.

3. What is Werkzeug and what role does it play in Flask?

Werkzeug is the WSGI utility library that Flask is built on top of. It handles the low-level HTTP plumbing so Flask itself can stay small:

  • Parsing HTTP requests into Flask's request object and building HTTP responses.
  • URL routing and matching (the Map/Rule system that powers @app.route).
  • The built-in development server (app.run()) and the interactive debugger (the "visual debugger" mentioned in Flask's feature list).
  • Utilities for cookies, file uploads (werkzeug.datastructures), and secure filename handling (secure_filename()).

4. What are the features of Flask Python?

  • Built-in web server and debugger
  • Compatibility with most of the latest technologies.
  • High scalability and flexibility for simple web applications.
  • Integrated support for unit testing
  • Securing cookies in client-side sessions
  • Dispatching RESTful request
  • Google App Engine compatibility
  • Unicode support
  • Web Server Gateway Interface(WSGI) compliance

5. What is the difference between Flask and Django?

Flask and Django are popular Python web frameworks used for web development.

Flask

  • Lightweight micro-framework.
  • Provides only the core features; extensions are added as needed.
  • Offers greater flexibility and control.
  • Easier to learn for small projects.
  • Best for REST APIs, microservices, and small to medium-sized applications.
  • Goal: Build lightweight and customizable web applications.

Django

  • Full-stack web framework with many built-in features.
  • Includes ORM, authentication, admin panel, security, and templating.
  • Follows the "batteries included" approach.
  • Suitable for large and complex applications.
  • Best for enterprise applications, CMS, and e-commerce websites.
  • Goal: Rapidly build secure and scalable web applications.

6. How is Flask different from FastAPI?

Flask and FastAPI are Python web frameworks used to build web applications and APIs. Flask is a lightweight and flexible web framework, whereas FastAPI is a modern, high-performance framework designed specifically for building fast RESTful APIs with automatic data validation and documentation.

Flask

  • Lightweight micro-framework.
  • Supports web applications and REST APIs.
  • Requires additional libraries for data validation and API documentation.
  • Supports synchronous programming by default.
  • Easy to learn and highly flexible.
  • Goal: Build lightweight web applications and APIs.

FastAPI

  • Modern framework built specifically for APIs.
  • Provides automatic request validation using Pydantic.
  • Automatically generates OpenAPI (Swagger) and ReDoc documentation.
  • Supports asynchronous programming (async/await) for high performance.
  • Uses Python type hints for validation and serialization.
  • Goal: Build fast, scalable, and production-ready APIs.

7. What is the default host port and port of Flask?

The default local host of a Flask dev server is 127.0.0.1, and the default port is 5000. Both can be overridden: app.run(host="0.0.0.0", port=8000).

8. why do we use Flask(__name__) in Flask?

  • The __name__ parameter is a Python built-in variable set to the name of the current module.
  • Passing __name__ to the Flask class constructor helps Flask determine the root path of the application, which it uses to locate resources such as templates (templates/) and static files (static/) relative to that module.

9. What is the Application Factory pattern in Flask, and why use it?

Instead of creating the Flask app object at module import time, an application factory is a function (conventionally create_app()) that builds and returns the configured app instance. This is the recommended pattern for any non-trivial Flask project because it:

  • Allows creating multiple instances of the app with different configs (e.g., one for testing, one for production) — impossible with a single global app object.
  • Avoids circular imports between blueprints and the app object.
  • Makes the app easy to unit test, since each test can spin up a fresh instance.
Python
# app/__init__.py
from flask import Flask

def create_app(config_object="config.DevelopmentConfig"):
    app = Flask(__name__)
    app.config.from_object(config_object)

    from .auth.routes import auth_bp
    from .blog.routes import blog_bp
    app.register_blueprint(auth_bp, url_prefix="/auth")
    app.register_blueprint(blog_bp, url_prefix="/blog")

    return app

# run.py
from app import create_app
app = create_app()
if __name__ == "__main__":
    app.run(debug=True)

10. How do you use the Flask CLI, and can you add your own commands?

The flask command (installed with Flask) reads the FLASK_APP environment variable to find your app and exposes built-in commands like flask run, flask shell, and flask routes.

Python
export FLASK_APP=run.py
export FLASK_DEBUG=1
flask run --host=0.0.0.0 --port=8000

You can also register custom CLI commands using @app.cli.command() — useful for one-off tasks like seeding a database:

Python
@app.cli.command("seed-db")
def seed_db():
    """Populate the database with sample data."""
    db.session.add_all([...])
    db.session.commit()
    print("Database seeded!")

Run it with flask seed-db.

11. Which databases is Flask compatible with?

  • Flask supports SQLite, MySQL, PostgreSQL, Oracle, and other SQL databases, most commonly through the Flask-SQLAlchemy extension, which wraps SQLAlchemy's ORM and eliminates the need to write raw SQL for common operations.
  • For NoSQL databases like MongoDB, Flask connects using Flask-MongoEngine or the plain pymongo driver.
  • These extensions ("DB adapters") standardize how Flask talks to different databases so the application code stays largely database-agnostic.

12. How long can an identifier be in Flask Python?

  • An identifier can be as long as you want; Python is case-sensitive, so it treats upper- and lower-case letters differently.
  • Reserved keywords (def, import, class, return, etc.) cannot be used as identifiers.
  • Identifiers must start with a letter or underscore, and the remaining characters can be letters, digits, or underscores.

13. What is routing in Flask?

  • App routing means mapping URLs to a specific function that handles the logic for that URL.
  • Modern web frameworks use meaningful URLs to help users remember them and navigate more simply.
  • For example, if the site's domain is www.example.org and we want to add routing to www.example.org/hello, we'd use @app.route("/hello").

14. What are variable rules (URL converters) in Flask?

Variable rules let you capture dynamic parts of a URL and pass them into the view function as arguments, optionally constrained by type using a converter.

Converter

Matches

string (default)

any text without a slash

int

positive integers

float

positive floating-point values

path

like string but also accepts slashes

uuid

UUID strings

Python
@app.route("/user/<string:username>")
def show_user(username):
    return f"User: {username}"

@app.route("/post/<int:post_id>")
def show_post(post_id):
    return f"Post number {post_id}"

@app.route("/files/<path:subpath>")
def show_file(subpath):
    return f"File path: {subpath}"

15. What is Template Inheritance in Flask?

  • Template Inheritance in Flask's Jinja2 engine allows you to define common elements once in a base template and reuse them across multiple pages using {% extends %} and {% block %}.
  • This avoids repeating HTML code and makes templates easier to maintain.

16. What is the difference between render_template() and render_template_string()?

Both render_template() and render_template_string() are Flask functions used to render HTML using the Jinja2 template engine. However, render_template() renders an HTML template stored in the application's templates folder, whereas render_template_string() renders an HTML template provided directly as a Python string.

render_template()

  • Renders an HTML file from the templates directory.
  • Uses Jinja2 templating.
  • Suitable for full web pages and reusable templates.
  • Easier to maintain for large applications.
  • Goal: Render external HTML template files.

render_template_string()

  • Renders a template directly from a string.
  • Uses Jinja2 syntax within the string.
  • Suitable for simple, dynamic, or temporary templates.
  • Not recommended for large HTML pages.
  • Goal: Render inline HTML templates.

17. How do you serve static files in Flask?

  • Flask automatically serves any file placed inside a static/ folder at the app root, at the URL path /static/<filename>.
  • In templates, always build the URL with url_for('static', filename=...) rather than hardcoding the path, so it stays correct if the static folder is renamed or the app is mounted under a prefix.
Python
app = Flask(__name__, static_folder="static", static_url_path="/assets")
HTML
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

18. What does url_for do in Flask?

The url_for() function generates a URL for a given function dynamically. It allows passing arguments to fill URL variables, so you don’t need to hard-code URLs in templates.

Example:

HTML
<a href="{{ url_for('get_post_id', post_id=post.id) }}">{{ post.title }}</a>

View function for handling variables in routes.

Python
@app.route("/blog/post/<string:post_id>")
def get_post_id(post_id):
    return post_id

19. What is flash() in Flask and how do you use it?

  • flash() stores a one-time message in the session that survives exactly one redirect, commonly used to show confirmation or error messages after a form submission.
  • The message is retrieved and cleared in the next template render using get_flashed_messages().
Python
from flask import flash, redirect, url_for

@app.route("/login", methods=["POST"])
def login():
    flash("Logged in successfully!", "success")
    return redirect(url_for("dashboard"))
HTML
{% for category, message in get_flashed_messages(with_categories=true) %}
  <div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}

20. What are class-based views (MethodView) in Flask?

  • Instead of writing a separate function per route and manually branching on request.method, Flask's flask.views.
  • MethodView lets you group HTTP-method handlers as methods on a class — useful for resource-style endpoints (common in REST APIs).
Python
from flask.views import MethodView

class UserAPI(MethodView):
    def get(self, user_id):
        return {"id": user_id}

    def delete(self, user_id):
        # delete logic
        return "", 204

app.add_url_rule("/user/<int:user_id>", view_func=UserAPI.as_view("user_api"))

21. In Flask, what do you mean by template engines?

Template engines help build web applications by separating HTML structure from Python code. They allow you to render dynamic content (like body, navigation, footer) on the server before sending it to the browser.

Popular template engines: Jinja2 (Flask), EJS, Pug, Mustache, HandlebarsJS, Blade.

22. What HTTP methods does Python Flask provide?

To handle HTTP requests, Flask uses a number of decorators. The HTTP protocol is the backbone of internet data communication. This HTTP protocol defines a number of techniques for obtaining information from a particular URL. The different HTTP methods are:

Request Purpose
 GETThe most widely used approach. The server responds with data after receiving a GET message.
 POSTTo submit HTML form data to the server, use this method. The server does not save the data supplied via the POST method.
 PUTUpload content to replace all current representations of the target resource.
 DELETEDeletes all current representations of the URL's target resource.
 HEADRetrieves the headers for a resource, without retrieving the resource itself.

23. How do you handle cookies in a Flask?

  • In Flask, cookies are set using response.set_cookie() and read using request.cookies.get().
  • Cookies store small pieces of data on the client's browser and are sent back to the server with each request; they're often used to track user actions, preferences, or session identifiers.

24. Explain how you can access sessions in Flask.

Flask sessions let you store data between client requests on the server side (or signed into a cookie by default). The session object can save user-specific information, like login state.

Python
from flask import Flask, render_template, request, redirect, session
from flask_session import Session

app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        session["name"] = request.form.get("name")
        return redirect("/")
    return render_template("login.html")

@app.route("/logout")
def logout():
    session.pop("name", None)
    return redirect("/")

login.html (the template rendered by the GET branch above):

HTML
<form method="POST">
    <label for="name">Enter your name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Login</button>
</form>

25. What is the g object? What distinguishes it from the session object?

  • The g object in Flask is a global namespace that stores data only for the current request, allowing different functions within the same request to access it.
  • For example, g.user and session object stores data across multiple requests for a specific user or browser, persisting until it expires or is cleared.
  • The main difference is that g is request-specific, while session is user-specific and persists across requests.

26. Explain Application Context and Request Context in Flask.

The Application Context is the context in which the Flask application runs — created when the app starts (or is first used) and destroyed when it's torn down. It stores configuration and other global application state, and holds current_app and g.

The Request Context is created fresh for every incoming HTTP request and destroyed once the response is sent (or on exception, via teardown handlers). It stores information about the current request — method, URL, headers, form data — and holds request and session.

27. What is a context processor in Flask?

A context processor is a function decorated with @app.context_processor that injects new variables automatically into the context of every template render, without having to pass them explicitly in every render_template() call — useful for things like the current year, logged-in user, or site-wide settings.

Python
@app.context_processor
def inject_globals():
    return {"site_name": "GeeksforGeeks", "current_year": 2026}
HTML
<footer>&copy; {{ current_year }} {{ site_name }}. All rights reserved.</footer>

site_name and current_year are available in every template automatically — no need to pass them in each render_template() call.

28. Explain how one can one-request database connections in Flask?

Opening and closing database connections for every request is inefficient. Flask provides decorators to manage connections for a single request:

  • before_request(): Runs before a request, ideal for opening a database connection.
  • after_request(): Runs after a request, used to close connections or modify the response.
  • teardown_request(): Runs after the request completes, even if an exception occurred, for cleanup tasks.

29. What do you mean by the Thread-Local object in Flask Python?

  • A thread-local object is tied to the current thread's ID and stored in a specialized structure.
  • Flask uses thread-local objects internally (via Werkzeug's context-local proxies) so request, session, and g behave like simple global variables inside a view, while actually staying isolated and thread-safe across concurrent requests.

30. How is memory managed in Flask Python?

  • Flask relies on Python's own memory management — objects are reference-counted, and an inbuilt garbage collector reclaims unused memory to free up heap space.
  • The interpreter tracks this automatically; developers can access lower-level tools via Python's gc module if needed, but rarely need to in typical Flask apps.

31. What is Flask-WTF, and what are its characteristics?

WTF, also known as WT Forms in Flask, is a type of interactive user interface. The WTF is a flask built-in module that lets you build forms in a different way in flask web apps. Flask-WTF is designed to be simple to connect with WTForms, and it works well with Flask-WTF.

  • Integration with web forms is available.
  • It comes with a CSRF token, it's an extremely secure form.
  • CSRF protection on a global scale 
  • Comes with the ability to integrate internationalization.
  • There's also a Supporting Captcha
  • This module has a file uploader that works with Flask Uploads.

32. How does CSRF protection work in Flask, and how do you enable it?

  • Cross-Site Request Forgery (CSRF) protection prevents malicious sites from submitting forged requests on behalf of a logged-in user.
  • Flask-WTF's CSRFProtect generates a unique, per-session token that must be included in every state-changing form (POST/PUT/DELETE) request; if the token is missing or doesn't match, Flask rejects the request with a 400 error.
Python
from flask_wtf import CSRFProtect

app.config["SECRET_KEY"] = "super-secret-key"
csrf = CSRFProtect(app)
HTML
<form method="POST">
    {{ form.hidden_tag() }}   <!-- injects the CSRF token automatically -->
    ...
</form>

33. How does file uploading work in Flask?

  • In Flask, file uploading is done via an HTML form with enctype="multipart/form-data".
  • The uploaded file is accessed on the server using request.files[] and saved to a desired location — always sanitize the filename with werkzeug.utils.secure_filename() to prevent path traversal.
Python
from flask import Flask, request
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(f"./uploads/{filename}")
    return "File uploaded successfully!"

upload.html (the form that submits to the route above — note enctype="multipart/form-data", required for file uploads to work at all):

HTML
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

34. How do you send a file back to the client in Flask?

Use send_file() for a single known file (in-memory or on disk), or send_from_directory() when serving files from a directory using a filename that may come from user input (it protects against directory-traversal attacks).

Python
from flask import send_from_directory

@app.route("/download/<path:filename>")
def download(filename):
    return send_from_directory("uploads", filename, as_attachment=True)

35. Mention how one can enable debugging in Flask Python?

When Debug is turned on, any changes to the application code are updated immediately in the development stage, eliminating the need to restart the server.

  • By setting the flag on the applications object
  • Bypassing the flag as a parameter to run. If the user enables debug support, the server will reload it when the code will change and the user doesn’t have to restart after each change made in the code.
Python
# Method 1
app.debug = True

# Method 2
app.run(host="localhost", debug=True)

36. How do you manage configuration for different environments (dev/test/prod) in Flask?

  • The recommended pattern is a set of config classes, one per environment, loaded via app.config.from_object() inside the application factory.
  • Secrets (DB URLs, API keys) are kept out of source control using environment variables and a .env file loaded with python-dotenv.
Python
# config.py
import os
from dotenv import load_dotenv
load_dotenv()

class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY")
    SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")

class DevelopmentConfig(Config):
    DEBUG = True

class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"

class ProductionConfig(Config):
    DEBUG = False
    
app.config.from_object("config.ProductionConfig")

37. What is Flask-SQLAlchemy?

Flask-SQLAlchemy is a Flask extension that integrates SQLAlchemy with Flask, making it easier to define models, interact with databases using Python classes, and manage database operations within a Flask application.

  • Provides seamless integration between Flask and SQLAlchemy.
  • Supports ORM-based model definition.
  • Handles database sessions automatically.
  • Compatible with multiple relational database systems.
  • Includes helper methods for common database tasks.

38. What is Flask-Migrate?

Flask-Migrate is a Flask extension that manages database schema changes using Alembic. It allows developers to create, apply, and roll back database migrations without manually modifying the database.

  • Tracks changes to database models.
  • Generates migration scripts automatically.
  • Supports upgrading and downgrading database schemas.
  • Uses Alembic as the migration engine.
  • Integrates seamlessly with Flask-SQLAlchemy.

39. Write a Flask-SQLAlchemy model and run a migration (hands-on).

Python
# models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f"<User {self.username}>"

40. What is logging in Flask?

  • Logging in Flask allows developers to track events and errors in their applications.
  • It uses Python's standard logging module under the hood, giving flexibility to create custom log handlers/formatters and monitor application behavior in production (app.logger.info(...), app.logger.error(...)).

41. What is Flask-Bcrypt?

Flask-Bcrypt is a Flask extension that provides password hashing using the bcrypt algorithm. It helps securely store user passwords by converting them into hashed values that are difficult to reverse.

  • Uses the bcrypt hashing algorithm for strong password security.
  • Supports password hashing and verification.
  • Protects passwords from plain-text storage.
  • Automatically adds a salt to each password.
  • Commonly used for user authentication systems.

42. How do you hash and verify a password using Flask-Bcrypt?

Python
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt(app)

# Hashing at signup
hashed_pw = bcrypt.generate_password_hash("mypassword").decode("utf-8")

# Verifying at login
is_valid = bcrypt.check_password_hash(hashed_pw, "mypassword")   # True

43. What is Flask-JWT?

Flask-JWT (or its more actively maintained successor, Flask-JWT-Extended) is a Flask extension that adds JSON Web Token (JWT)-based authentication to Flask applications. It enables secure user authentication by issuing and validating tokens instead of relying on server-side sessions.

  • Implements JWT-based authentication.
  • Generates and validates access tokens.
  • Supports stateless authentication.
  • Secures protected API endpoints.
  • Commonly used in RESTful APIs.

44. How do you implement JWT-based authentication in Flask?

Python
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity

app.config["JWT_SECRET_KEY"] = "super-secret"
jwt = JWTManager(app)

@app.route("/login", methods=["POST"])
def login():
    # validate username/password here...
    token = create_access_token(identity="geek_user")
    return {"access_token": token}

@app.route("/protected")
@jwt_required()
def protected():
    current_user = get_jwt_identity()
    return {"logged_in_as": current_user}

45. What is Role-Based Access Control (RBAC), and how would you implement it in Flask?

  • RBAC restricts access to routes/resources based on a user's assigned role (e.g., admin, editor, viewer) rather than checking identity alone.
  • In Flask it's usually implemented as a custom decorator that checks current_user.role (from Flask-Login or JWT claims) before allowing the view to run.
Python
from functools import wraps
from flask import abort
from flask_login import current_user

def role_required(role):
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            if not current_user.is_authenticated or current_user.role != role:
                abort(403)
            return f(*args, **kwargs)
        return wrapped
    return decorator

@app.route("/admin/dashboard")
@role_required("admin")
def admin_dashboard():
    return "Welcome, admin!"

46. How do you enable CORS in a Flask application?

  • Cross-Origin Resource Sharing (CORS) must be explicitly enabled when a frontend (e.g., a React app on a different port/domain) needs to call your Flask API.
  • The flask-cors extension adds the required Access-Control-Allow-* headers automatically.
Python
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://myfrontend.com"}})

47. How to get a visitor IP address in Flask?

To get the visitor IP address in Flask we use method request.remote_addr Below is the implementation of it:

Python
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def get_visitor_ip():
    visitor_ip = request.remote_addr
    return f"Visitor's IP address is: {visitor_ip}"

if __name__ == '__main__':
    app.run(debug=True)

48. What is the use of jsonify() in Flask?

  • jsonify() converts Python data to JSON and returns it as a response with the correct application/json content type.
  • It simplifies building APIs by automatically setting headers and formatting data properly, unlike json.dumps(), which only returns a plain JSON string with no content-type handling.

49. How do you create a RESTful application in Flask?

Flask-RESTful is a Flask extension for building REST APIs on top of Flask. General steps:

  1. Import the modules and set up the app.
  2. Define the REST API endpoints (resources).
  3. Define the supported request methods per endpoint.
  4. Implement the endpoint handlers (business logic).
  5. Serialize the data (Python objects → JSON).
  6. Add error handling.
  7. Test the endpoints using tools like Postman or curl.

50. Write a simple CRUD REST API in Flask

Python
from flask import Flask, request, jsonify

app = Flask(__name__)
books = [{"id": 1, "title": "Flask Basics"}]

@app.route("/api/books", methods=["GET"])
def get_books():
    return jsonify(books), 200

@app.route("/api/books", methods=["POST"])
def add_book():
    data = request.get_json()
    new_book = {"id": len(books) + 1, "title": data["title"]}
    books.append(new_book)
    return jsonify(new_book), 201

@app.route("/api/books/<int:book_id>", methods=["PUT"])
def update_book(book_id):
    data = request.get_json()
    for b in books:
        if b["id"] == book_id:
            b["title"] = data["title"]
            return jsonify(b), 200
    return jsonify({"error": "Not found"}), 404

@app.route("/api/books/<int:book_id>", methods=["DELETE"])
def delete_book(book_id):
    global books
    books = [b for b in books if b["id"] != book_id]
    return "", 204

51. What is serialization and deserialization in the context of Flask REST APIs?

  • Serialization converts Python/ORM objects into a transmittable format like JSON to send in a response.
  • Deserialization is the reverse — parsing incoming JSON from a request body back into Python objects, usually with validation.
  • Libraries like Marshmallow or Flask-RESTful's fields are commonly used to define schemas that handle both directions consistently, including type checking and required-field validation.

52. What is Flask-RESTful?

Flask-RESTful is a Flask extension that simplifies building RESTful APIs. It provides tools to define API endpoints as resource classes, handle HTTP methods, serialize data, and manage responses, making it easier to create structured and maintainable APIs in Flask applications.

53. What is middleware in Flask, and how do you write custom WSGI middleware?

Middleware wraps the WSGI application from the outside — it can inspect or modify the request before Flask's routing even runs, and modify the response after Flask has finished, making it useful for cross-cutting concerns like logging, authentication headers, or fixing proxy headers.

Python
class SimpleLoggingMiddleware:
    def __init__(self, wsgi_app):
        self.wsgi_app = wsgi_app

    def __call__(self, environ, start_response):
        print(f"Incoming request: {environ['PATH_INFO']}")
        return self.wsgi_app(environ, start_response)

app.wsgi_app = SimpleLoggingMiddleware(app.wsgi_app)

54. Does Flask support asynchronous views? Explain how, and its limitations.

Since Flask 2.0, view functions can be declared async def, and Flask will run them for you:

Python
@app.route("/data")
async def get_data():
    result = await some_async_db_call()
    return jsonify(result)

Limitations:

  • Flask itself is still fundamentally a WSGI framework under the hood, each async view is run in its own event loop per request via asgiref, so you don't get the same concurrency benefits as a native ASGI framework .
  • Async in Flask mainly helps when a single view needs to await several I/O calls concurrently, not for scaling the number of simultaneous requests the server can handle.

55. What is Flask-SocketIO?

Flask-SocketIO is a Flask extension that enables real-time, bidirectional communication between clients and the server using WebSockets and the Socket.IO protocol.

  • Supports real-time data exchange.
  • Enables event-driven communication.
  • Works with WebSockets and fallback transports.
  • Handles multiple client connections efficiently.
  • Commonly used for chat apps, live notifications, and dashboards.

56. What is Flask Sijax?

Flask-Sijax is a Flask extension that integrates Sijax (Simple Ajax) with Flask, allowing developers to handle AJAX requests on the server using Python instead of writing JavaScript for common interactions.

  • Simplifies AJAX request handling.
  • Executes server-side Python functions for client actions.
  • Reduces the need for custom JavaScript.
  • Supports dynamic page updates without full reloads.
  • Useful for interactive web applications.

57. What is a Flask blueprint?

  • A Flask blueprint is a way to structure an application into smaller, modular, reusable components.
  • It lets you define routes, templates, and static files in a self-contained unit that is later registered with the main application — the standard way to organize any Flask app beyond a single file.
Python
# blog/routes.py
from flask import Blueprint

blog_bp = Blueprint("blog", __name__, template_folder="templates")

@blog_bp.route("/posts")
def list_posts():
    return "All posts"

# app/__init__.py
from blog.routes import blog_bp
app.register_blueprint(blog_bp, url_prefix="/blog")
# now reachable at /blog/posts

58. Why is Flask called a Microframework?

  • Flask is called a microframework because it has a small core with only essential features — routing, request handling, and blueprints.
  • Other features such as ORM, authentication, and caching are available through optional extensions.
  • This "small core + extensions" design keeps Flask lightweight, easy to learn, and flexible to scale to whatever a given project needs.

59. What type of applications can we build with Flask?

Flask can be used to build a wide range of web applications, from small websites to large, scalable web services. Its lightweight and modular design makes it suitable for projects of all sizes.

Types of Applications:

  • Static and dynamic websites.
  • RESTful APIs and backend services.
  • E-commerce and business applications.
  • Content Management Systems (CMS).
  • Real-time applications using Flask-SocketIO.
  • Machine learning and data visualization web apps.
  • Authentication and admin dashboards.

60. What is Flask-Assets?

Flask-Assets is a Flask extension that manages and optimizes static assets such as CSS and JavaScript files. It supports bundling, minification, and compression to improve application performance.

  • Bundles multiple CSS and JavaScript files.
  • Minifies and compresses static assets.
  • Reduces page load time.
  • Integrates with the webassets library.
  • Helps organize and manage frontend resources.

61. What is Flask-Admin?

Flask-Admin is a Flask extension that provides a ready-to-use administrative interface for managing application data. It automatically generates admin pages for database models and other resources with minimal configuration.

  • Creates an admin dashboard quickly.
  • Supports CRUD operations on database records.
  • Integrates with Flask-SQLAlchemy and other ORMs.
  • Allows customization of forms and views.
  • Includes authentication support for secure access.

62. How do you handle errors in Flask?

Flask lets you register custom handlers for specific HTTP error codes or exception classes using @app.errorhandler(), so you can return a friendly page/JSON instead of the default error output.

Python
from flask import jsonify

@app.errorhandler(404)
def not_found(e):
    return jsonify(error="Resource not found"), 404

@app.errorhandler(500)
def server_error(e):
    return jsonify(error="Internal server error"), 500

63. How do you write unit tests for a Flask application?

Flask ships with a built-in test client (app.test_client()) that simulates HTTP requests without running a real server — commonly used with pytest.

Python
# conftest.py
import pytest
from app import create_app

@pytest.fixture
def client():
    app = create_app("config.TestingConfig")
    with app.test_client() as client:
        yield client

# test_routes.py
def test_home_page(client):
    response = client.get("/")
    assert response.status_code == 200

def test_create_book(client):
    response = client.post("/api/books", json={"title": "New Book"})
    assert response.status_code == 201
    assert response.get_json()["title"] == "New Book"

Run with pytest. Setting app.config["TESTING"] = True also disables error-catching during request handling, so exceptions propagate to the test instead of returning a generic 500 page.

64. How do you deploy a Flask application to production, and why not use app.run() there?

The built-in development server (app.run()) is single-threaded, unoptimized, and not designed to handle production traffic or concurrent connections safely — it even prints a warning about this. In production, Flask apps are typically served by:

1. A WSGI application server — Gunicorn or uWSGI — which runs multiple worker processes/threads:

gunicorn -w 4 -b 0.0.0.0:8000 "app:create_app()"

2. A reverse proxy (Nginx) in front of it, handling TLS termination, static file serving, and load balancing.

3. Often, the whole stack is containerized with Docker for reproducible deployment:

FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install -r requirements.txt

COPY . .

CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "app:create_app()"]

4. Or deployed to a PaaS like Heroku, using a Procfile: web: gunicorn app:create_app().

Comment