Django & Flask Topic
Interview questions covering Django and Flask for experienced Python developers.
Django-Specific Questions
1. What is the difference between a Project and an App in Django?
Answer:
-
Project: A collection of configuration and apps for a specific website. A project can contain multiple apps. It's the entire application with settings, URLs, and deployed configuration.
-
App: A web application that does something specific (e.g., blog, user authentication, poll system). An app can be in multiple projects. It's a self-contained module that follows the "pluggable" design principle.
python
# Creating a project and app
django-admin startproject mysite
python manage.py startapp myapp
2. Explain Django's MVT (Model-View-Template) architecture.
Answer:
-
Model: Represents the data structure and database schema. Handles data validation and business logic.
-
View: The business logic layer. Processes requests, interacts with models, and returns responses.
-
Template: The presentation layer. HTML with Django Template Language for dynamic content rendering.
Flow: URL → View (handles logic) → Model (fetches data) → Template (renders HTML) → Response
3. How does Django's ORM work and what are its advantages?
Answer:
Django ORM (Object-Relational Mapping) is an abstraction layer that lets you interact with the database using Python classes and methods instead of SQL.
Advantages:
-
Database agnostic (supports PostgreSQL, MySQL, SQLite, Oracle)
-
Security against SQL injection
-
Clean, Pythonic API
-
Built-in query optimization
-
Migrations system
python
# Example ORM usage
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
# Querying
users = User.objects.filter(name__startswith='John')
4. What are Django Class-Based Views (CBVs) and when would you use them?
Answer:
CBVs are views implemented as Python classes rather than functions. They promote code reuse through inheritance and mixins.
Use Cases:
-
CRUD operations:
CreateView,UpdateView,DeleteView,ListView,DetailView -
When you need reusable view logic
-
Complex views with multiple HTTP methods
python
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
context_object_name = 'articles'
paginate_by = 20
5. Explain Django's middleware and how to create custom middleware.
Answer:
Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level plugin system.
Creating custom middleware:
python
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Code executed on each request before the view
print(f"Processing request: {request.path}")
response = self.get_response(request)
# Code executed on each response after the view
print(f"Returning response for: {request.path}")
return response
6. How does Django handle database migrations?
Answer:
Django migrations are version control for your database schema. They allow you to evolve your database schema over time.
Process:
-
Make changes to models
-
Create migration files:
python manage.py makemigrations -
Apply migrations:
python manage.py migrate -
Track migration history in
django_migrationstable
Key commands:
-
makemigrations: Creates new migrations based on model changes -
migrate: Applies migrations to the database -
showmigrations: Shows migration status -
sqlmigrate: Shows SQL for a migration
7. What is Django's signals framework and when should it be used?
Answer:
Signals allow certain senders to notify a set of receivers when some action has occurred. They're used for decoupled applications.
Common built-in signals:
-
pre_save,post_save -
pre_delete,post_delete -
request_started,request_finished
python
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
Use sparingly: Can make code harder to follow and debug.
8. How do you optimize database queries in Django?
Answer:
-
select_related(): For ForeignKey and OneToOne relationships (SQL JOIN) -
prefetch_related(): For ManyToMany and reverse ForeignKey relationships (separate query) -
only()anddefer(): To load only specific fields -
Database indexing on frequently queried fields
-
Use
count()instead oflen(queryset)for counting -
Avoid N+1 queries by using
select_relatedandprefetch_related
python
# Bad: N+1 queries
for book in Book.objects.all():
print(book.author.name) # Database hit for each book
# Good: 1 query with join
for book in Book.objects.select_related('author').all():
print(book.author.name) # No additional queries
9. Explain Django's authentication system.
Answer:
Django provides a built-in authentication system that handles:
-
User accounts and profiles
-
Permissions and groups
-
Password hashing and validation
-
Login/logout sessions
-
Password reset functionality
Key components:
-
django.contrib.authpackage -
Usermodel (extensible withAUTH_USER_MODEL) -
Authentication backends
-
Decorators:
@login_required,@permission_required
10. What are Django REST Framework (DRF) serializers and their types?
Answer:
Serializers convert complex data types (like querysets, model instances) to native Python datatypes that can be rendered into JSON/XML.
Types of serializers:
-
Serializer: Basic serializer, similar to Django Forms -
ModelSerializer: Automatically generates fields based on model -
HyperlinkedModelSerializer: Similar to ModelSerializer but uses hyperlinks for relationships
python
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'price', 'description']
read_only_fields = ['id']
Flask-Specific Questions
11. Explain Flask's application and request contexts.
Answer:
Flask uses contexts to make certain variables globally accessible for a single request or application lifetime.
-
Application Context: Tracks application-level data (
current_app,g) -
Request Context: Tracks request-level data (
request,session)
python
from flask import Flask, request, current_app, g
app = Flask(__name__)
@app.route('/')
def index():
# request is available due to request context
user_agent = request.headers.get('User-Agent')
# current_app refers to the Flask app instance
app_name = current_app.name
# g is for storing data during request
g.database_connection = create_connection()
return f'Hello from {app_name}'
12. What are Flask Blueprints and why are they useful?
Answer:
Blueprints are a way to organize related routes, templates, and static files into reusable components. They help structure large applications.
Benefits:
-
Modular application structure
-
Reusable components across projects
-
Separate concerns by feature
python
# auth/blueprint.py
from flask import Blueprint
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
@auth_bp.route('/login')
def login():
return 'Login page'
@auth_bp.route('/register')
def register():
return 'Register page'
# app.py
from auth.blueprint import auth_bp
app.register_blueprint(auth_bp)
13. How do you handle database operations in Flask?
Answer:
Flask doesn't include a built-in ORM like Django. Common approaches:
-
SQLAlchemy (most popular): Full-featured ORM
-
Flask-SQLAlchemy: Flask extension that simplifies SQLAlchemy integration
-
Raw SQL with database drivers
-
Other ORMs: Peewee, PonyORM
python
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)
@app.route('/users')
def users():
users = User.query.all()
return render_template('users.html', users=users)
14. What is the purpose of Flask's g object?
Answer:
The g object is a namespace object that stores data during a request. It's reset for each new request.
Common use cases:
-
Storing database connections
-
Caching computed values during a request
-
Storing user information after authentication
python
from flask import g
import sqlite3
def get_db():
if 'db' not in g:
g.db = sqlite3.connect('database.sqlite')
return g.db
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'db'):
g.db.close()
15. Explain Flask's template inheritance system.
Answer:
Flask uses Jinja2 templating which supports template inheritance, allowing you to build a base template with blocks that child templates can override.
jinja2
<!-- base.html -->
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<div class="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
<!-- child.html -->
{% extends "base.html" %}
{% block title %}My Page - My Site{% endblock %}
{% block content %}
<h1>Welcome to my page!</h1>
<p>This is the content.</p>
{% endblock %}
16. How do you implement authentication in Flask?
Answer:
Flask doesn't have built-in authentication like Django. Common approaches:
-
Flask-Login: For session-based authentication
-
Flask-JWT-Extended: For JWT token-based authentication
-
OAuth libraries: For social authentication
-
Custom implementation
python
from flask_login import LoginManager, UserMixin, login_user, login_required
login_manager = LoginManager()
class User(UserMixin):
def __init__(self, id):
self.id = id
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
@app.route('/login')
def login():
user = User(1)
login_user(user)
return "Logged in"
@app.route('/protected')
@login_required
def protected():
return "Protected area"
17. What are Flask application factories and why use them?
Answer:
Application factories are functions that return a Flask application instance. They enable:
-
Testing with different configurations
-
Multiple application instances
-
Better project organization
-
Dynamic configuration
python
def create_app(config_filename=None):
app = Flask(__name__)
if config_filename:
app.config.from_pyfile(config_filename)
else:
app.config.from_envvar('APP_SETTINGS')
# Initialize extensions
db.init_app(app)
login_manager.init_app(app)
# Register blueprints
from .auth import auth_bp
app.register_blueprint(auth_bp)
return app
# Usage
app = create_app('config.py')
18. How do you handle configuration in Flask applications?
Answer:
Flask provides flexible configuration handling:
python
app = Flask(__name__)
# Method 1: Direct assignment
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'your-secret-key'
# Method 2: From object
app.config.from_object('configmodule.Config')
# Method 3: From environment variable
app.config.from_envvar('APP_SETTINGS')
# Method 4: From pyfile
app.config.from_pyfile('config.py')
# config.py example
class Config:
DEBUG = False
TESTING = False
SECRET_KEY = 'development-key'
DATABASE_URI = 'sqlite:///app.db'
class ProductionConfig(Config):
DATABASE_URI = 'postgresql://user@localhost/prod_db'
class DevelopmentConfig(Config):
DEBUG = True
19. Explain Flask's error handling mechanisms.
Answer:
Flask provides decorators to register custom error handlers for specific HTTP status codes or exceptions.
python
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback() # In case of database errors
return render_template('500.html'), 500
@app.errorhandler(Exception)
def handle_all_exceptions(error):
# Log the error
app.logger.error(f'Unhandled exception: {error}')
return render_template('error.html'), 500
20. Compare and contrast Django vs Flask for different use cases.
Answer:
| Aspect | Django | Flask |
|---|---|---|
| Type | "Batteries-included" full-stack framework | Microframework, minimal core |
| Learning Curve | Steeper due to more concepts | Gentler, easier to start |
| Database ORM | Built-in, excellent ORM | Requires extensions (SQLAlchemy) |
| Admin Interface | Built-in, powerful admin | None built-in |
| Flexibility | Opinionated, follows "Django way" | Very flexible, choose your components |
| Use Cases | Content-heavy sites, CMS, complex apps | APIs, microservices, simple web apps |
| Project Size | Better for large, complex projects | Better for small to medium projects |
When to choose Django:
-
Building complex, database-driven websites
-
Need built-in admin, authentication, ORM
-
Large team with need for structure and conventions
-
Rapid development of full-featured applications
When to choose Flask:
-
Building APIs or microservices
-
Need maximum flexibility in architecture
-
Simple applications or prototypes
-
When you want to choose specific components (ORM, auth, etc.)
These questions cover the essential concepts and practical knowledge needed for senior-level Django and Flask positions. The answers demonstrate both technical depth and real-world application experience.
Comments (0)
No comments yet. Be the first to comment!