Advanced Flask Interview Questions and Answers

Author

Kritim Yantra

Feb 24, 2025

Advanced Flask Interview Questions and Answers

Flask Python Framework: A Comprehensive Guide and Advanced Interview Q&A

Flask is a lightweight and flexible micro-framework for Python designed to make web application development simple and efficient. Known for its modularity and ease of use, Flask allows developers to build scalable applications with minimal boilerplate. Below, we dive into 30 advanced interview questions and answers to help you master Flask concepts.


Advanced Flask Interview Questions and Answers

1. Explain Flask's Application and Request Contexts

Answer:
Flask uses two contexts: Application Context and Request Context.

  • Application Context tracks application-level data (e.g., database connections) and is created when a request is handled or a CLI command runs. It contains g (global variables) and current_app (the active Flask instance).
  • Request Context tracks request-specific data (e.g., URL parameters) and includes request and session.
from flask import current_app, g, request

@app.route('/')
def home():
    # Access application context
    app_name = current_app.name
    # Access request context
    user_agent = request.headers.get('User-Agent')
    return f"Welcome to {app_name}! User Agent: {user_agent}"

2. How to Handle Database Migrations in Flask?

Answer:
Use Flask-Migrate (built on Alembic) to manage database schema changes.

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# CLI commands:
# flask db init
# flask db migrate -m "Initial migration"
# flask db upgrade

3. What Are Flask Blueprints? Provide an Example

Answer:
Blueprints organize related routes and templates into reusable components.

# auth.py blueprint
from flask import Blueprint

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login')
def login():
    return "Login Page"

# app.py
from auth import auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')

4. How to Implement JWT Authentication in Flask?

Answer:
Use Flask-JWT-Extended to handle JSON Web Tokens.

from flask_jwt_extended import JWTManager, jwt_required, create_access_token

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

@app.route('/login', methods=['POST'])
def login():
    access_token = create_access_token(identity='user_id')
    return {'token': access_token}

@app.route('/protected')
@jwt_required()
def protected():
    return "Protected Route"

5. Explain Flask's CLI and Custom Commands

Answer:
Flask integrates with Click to create CLI commands.

@app.cli.command('greet')
@click.argument('name')
def greet(name):
    print(f"Hello, {name}!")

# Run: flask greet "Alice"

6. How Does Flask Handle Static Files?

Answer:
By default, Flask serves static files (CSS, JS) from the /static directory. Use url_for('static', filename='style.css') to reference them.

<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">

7. Flask vs. Django: Key Differences

Answer:

  • Flask: Micro-framework, minimalistic, flexible, requires manual setup for databases/auth.
  • Django: "Batteries-included," ORM, admin panel, built-in auth.

8. How to Create a RESTful API with Flask?

Answer:
Use Flask-RESTful or plain Flask with JSON responses.

from flask import jsonify

@app.route('/api/users')
def get_users():
    users = [{'id': 1, 'name': 'Alice'}]
    return jsonify(users)

9. How to Use Middleware in Flask?

Answer:
Wrap the app with WSGI middleware.

class SimpleMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        print("Before request")
        response = self.app(environ, start_response)
        print("After request")
        return response

app.wsgi_app = SimpleMiddleware(app.wsgi_app)

10. Handling Asynchronous Tasks in Flask

Answer:
Use Celery for background tasks.

from celery import Celery

celery = Celery(app.name, broker='redis://localhost:6379/0')

@celery.task
def send_email(email):
    # Send email asynchronously
    pass

@app.route('/notify')
def notify():
    send_email.delay('user@example.com')
    return "Notification sent!"

11. Securing Flask Applications

Answer:

  • Use HTTPS.
  • Sanitize inputs to prevent SQLi/XSS.
  • Set SESSION_COOKIE_SECURE=True.
  • Use flask-talisman for security headers.

12. Using SQLAlchemy with Flask

Answer:
Flask-SQLAlchemy provides ORM integration.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

@app.route('/users')
def users():
    users = User.query.all()
    return jsonify([user.name for user in users])

13. Purpose of before_request and after_request

Answer:

  • before_request: Runs before each request (e.g., opening DB connections).
  • after_request: Runs after each request (e.g., adding headers).
@app.before_request
def before_request():
    g.db = connect_db()

@app.after_request
def after_request(response):
    g.db.close()
    return response

14. Scaling Flask Applications

Answer:

  • Use Gunicorn/uWSGI with multiple workers.
  • Load balance with Nginx.
  • Cache with Redis.
  • Database connection pooling.

15. Implementing Caching in Flask

Answer:
Use Flask-Caching.

from flask_caching import Cache

cache = Cache(app, config={'CACHE_TYPE': 'RedisCache'})

@app.route('/slow-route')
@cache.cached(timeout=60)
def slow_route():
    # Expensive computation
    return "Result"

Here are the remaining 15 advanced Flask interview questions and answers in a rich-text format suitable for posting on your Kritim Yantra website.


16. Signals in Flask

Answer:
Flask uses the Blender library to provide signals that allow decoupled components to react to events.

from flask import template_rendered

def log_template_rendered(sender, template, context):
    print(f"Template {template.name} rendered")

template_rendered.connect(log_template_rendered, app)

17. Flask Extensions and Their Uses

Answer:
Flask extensions provide additional functionality. Some popular ones:

  • Flask-SQLAlchemy → Database ORM
  • Flask-Migrate → Database Migrations
  • Flask-Login → Authentication
  • Flask-WTF → Forms Handling
  • Flask-JWT-Extended → JWT Authentication

18. Difference Between Flask and FastAPI

Answer:

Feature Flask FastAPI
Speed Slower Faster (Uses async)
Type Hinting Optional Enforced
Performance Lower High (Asynchronous)
API Docs Manual Automatic (Swagger)

FastAPI is preferred for high-performance APIs, whereas Flask is easier for general web apps.


19. Implementing OAuth Authentication in Flask

Answer:
Use Flask-OAuthlib or Authlib for OAuth authentication.

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
google = oauth.register(
    name='google',
    client_id='your_client_id',
    client_secret='your_client_secret',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    client_kwargs={'scope': 'email profile'}
)

@app.route('/login')
def login():
    return google.authorize_redirect(url_for('authorize', _external=True))

20. Difference Between @app.route() and @app.add_url_rule()

Answer:

  • @app.route() → A decorator that directly maps a function to a URL.
  • app.add_url_rule() → Allows dynamic URL registration.
def index():
    return "Hello Flask!"

app.add_url_rule('/', 'index', index)

21. CSRF Protection in Flask

Answer:
Use Flask-WTF for CSRF protection.

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)

22. Flask Sessions vs. Flask Cookies

Answer:

  • Cookies: Stored on the client-side (browser).
  • Sessions: Stored server-side (Flask uses cookies to track session IDs).
from flask import session

@app.route('/set-session')
def set_session():
    session['user'] = 'admin'
    return "Session Set"

23. Logging in Flask Applications

Answer:
Flask uses Python's logging module.

import logging

logging.basicConfig(level=logging.DEBUG)
app.logger.info("Application started")

24. Web Scraping with Flask

Answer:
Use Requests and BeautifulSoup.

import requests
from bs4 import BeautifulSoup

@app.route('/scrape')
def scrape():
    response = requests.get('https://example.com')
    soup = BeautifulSoup(response.text, 'html.parser')
    return soup.title.string

25. Flask Internationalization (i18n) and Localization (l10n)

Answer:
Use Flask-Babel for multilingual support.

from flask_babel import Babel

babel = Babel(app)

@app.route('/greet')
def greet():
    return gettext("Hello, World!")

26. Flask Dependency Injection with Flask-Injector

Answer:
Use Flask-Injector for dependency injection.

from flask_injector import FlaskInjector

class Service:
    def get_data(self):
        return "Hello, Dependency Injection!"

def configure(binder):
    binder.bind(Service, to=Service, scope=singleton)

FlaskInjector(app=app, modules=[configure])

27. Flask and GraphQL API with Flask-GraphQL

Answer:
Use Flask-GraphQL to create GraphQL APIs.

from flask_graphql import GraphQLView
from graphene import ObjectType, String, Schema

class Query(ObjectType):
    hello = String()

    def resolve_hello(self, info):
        return "Hello, GraphQL!"

schema = Schema(query=Query)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))

28. Creating Background Jobs with RQ (Redis Queue)

Answer:
Use Flask-RQ2 for async tasks.

from flask_rq2 import RQ

rq = RQ(app)

@rq.job
def background_task():
    return "Task Completed!"

@app.route('/run-task')
def run_task():
    background_task.queue()
    return "Task Queued!"

29. Monitoring Flask Performance with Prometheus

Answer:
Use Prometheus-Client for monitoring.

from prometheus_client import Counter

request_count = Counter('flask_requests_total', 'Total Flask Requests')

@app.route('/')
def index():
    request_count.inc()
    return "Hello, Flask!"

30. Flask and Celery Integration

Answer:
Use Celery for async job processing.

from celery import Celery

celery = Celery(app.name, broker='redis://localhost:6379/0')

@celery.task
def send_email(email):
    # Send email asynchronously
    pass

@app.route('/send-mail')
def send_mail():
    send_email.delay('user@example.com')
    return "Mail Sent!"

Conclusion

Flask's simplicity and extensibility make it ideal for building everything from small apps to large-scale systems. Mastering these advanced concepts ensures you're prepared to tackle complex scenarios and excel in Flask-focused interviews.

Tags

Python Flask

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google