Kritim Yantra
Feb 24, 2025
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.
Answer:
Flask uses two contexts: Application Context and Request Context.
g
(global variables) and current_app
(the active Flask instance).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}"
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
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')
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"
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"
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">
Answer:
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)
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)
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!"
Answer:
SESSION_COOKIE_SECURE=True
.flask-talisman
for security headers.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])
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
Answer:
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.
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)
Answer:
Flask extensions provide additional functionality. Some popular ones:
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.
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))
@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)
Answer:
Use Flask-WTF for CSRF protection.
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
Answer:
from flask import session
@app.route('/set-session')
def set_session():
session['user'] = 'admin'
return "Session Set"
Answer:
Flask uses Python's logging module.
import logging
logging.basicConfig(level=logging.DEBUG)
app.logger.info("Application started")
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
Answer:
Use Flask-Babel for multilingual support.
from flask_babel import Babel
babel = Babel(app)
@app.route('/greet')
def greet():
return gettext("Hello, World!")
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])
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))
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!"
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!"
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!"
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.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google