Django面试通关2024:从基础到高并发实战题库与深度解析

引言:Django面试的新时代挑战
在2024年的技术招聘市场中,Django作为Python生态中最成熟的Web框架,依然是后端开发岗位的热门选择。然而,随着云原生、微服务和高并发场景的普及,面试官对Django开发者的考察已经从简单的CRUD操作转向了架构设计、性能优化和分布式系统理解。本文将系统性地梳理Django面试的核心知识体系,从基础概念到高并发实战,帮助求职者构建完整的技能树。
现代Django面试通常分为四个层次:基础语法与ORM机制、中间件与请求生命周期、性能优化与架构设计、高并发场景实战。每个层次都对应着不同的岗位要求,初级开发者需要掌握前两个层次,而高级开发者则必须精通后两个层次。我们将通过详细的理论解析和完整的代码示例,帮助你深入理解每个知识点。
第一部分:Django基础核心考点深度解析
1.1 Django请求生命周期详解
Django的请求生命周期是面试中最常被问到的基础问题,它考察的是开发者对框架整体架构的理解。当一个HTTP请求到达Django应用时,会经历一系列有序的处理步骤。
首先,请求经过WSGI服务器(如Gunicorn或uWSGI)被转换为Django可识别的HttpRequest对象。随后,请求会通过一系列中间件(Middleware),这是Django提供的钩子机制,允许我们在请求处理的不同阶段插入自定义逻辑。
# 自定义中间件示例:记录请求处理时间
import time
from django.utils.deprecation import MiddlewareMixin

class RequestTimingMiddleware(MiddlewareMixin):
def process_request(self, request):
request._start_time = time.time()
print(f”开始处理请求: {request.method} {request.path}”)

def process_response(self, request, response):
if hasattr(request, ‘_start_time’):
duration = time.time() – request._start_time
print(f”请求处理完成,耗时: {duration:.4f}秒”)
return response

def process_view(self, request, view_func, view_args, view_kwargs):
print(f”即将调用视图函数: {view_func.__name__}”)
return None
中间件处理完成后,Django会根据URL配置进行路由匹配,找到对应的视图函数。视图函数处理业务逻辑后返回HttpResponse对象,该对象再反向经过中间件的response钩子,最终返回给客户端。理解这个流程对于调试和性能优化至关重要,因为任何环节的阻塞都会影响整体响应时间。
1.2 ORM深度解析与查询优化
Django的ORM是其最强大的特性之一,但也是面试中的重点考察对象。ORM的核心在于将数据库操作转换为Python对象操作,同时提供了强大的查询接口。
# models.py 定义示例
from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
STATUS_CHOICES = [
(‘draft’, ‘草稿’),
(‘published’, ‘已发布’),
(‘archived’, ‘已归档’),
]

title = models.CharField(max_length=200, db_index=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name=’articles’)
content = models.TextField()
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=’draft’)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
view_count = models.IntegerField(default=0)

class Meta:
ordering = [‘-created_at’]
indexes = [
models.Index(fields=[‘status’, ‘created_at’]),
]

def __str__(self):
return self.title
在查询优化方面,N+1查询问题是必须掌握的陷阱。以下是一个典型的N+1问题及其解决方案:
# 错误的写法:会产生N+1查询
def get_articles_n_plus_one():
articles = Article.objects.filter(status=’published’)[:10]
for article in articles:
# 每次循环都会查询数据库获取作者信息
print(f”{article.title} by {article.author.username}”)

# 正确的写法:使用select_related或prefetch_related
def get_articles_optimized():
# select_related用于外键和一对一关系
articles = Article.objects.select_related(‘author’).filter(status=’published’)[:10]
for article in articles:
# 作者信息已在初始查询中获取
print(f”{article.title} by {article.author.username}”)

# 多对多关系使用prefetch_related
class Tag(models.Model):
name = models.CharField(max_length=50)
articles = models.ManyToManyField(Article, related_name=’tags’)

def get_articles_with_tags():
# 预加载标签信息
articles = Article.objects.prefetch_related(‘tags’).filter(status=’published’)[:10]
for article in articles:
tags = [tag.name for tag in article.tags.all()]
print(f”{article.title} – 标签: {‘, ‘.join(tags)}”)
1.3 Django信号机制与应用场景
信号(Signals)是Django提供的解耦机制,允许特定动作发生时触发接收函数。这在面试中常被问到如何实现模型变更的自动处理。
from django.db.models.signals import post_save, pre_delete, m2m_changed
from django.dispatch import receiver
from django.core.cache import cache
from .models import Article

# 当文章保存后更新缓存
@receiver(post_save, sender=Article)
def update_article_cache(sender, instance, created, **kwargs):
cache_key = f’article_{instance.id}’
if created:
cache.set(cache_key, instance, 3600)
print(f”文章创建,缓存已设置: {instance.title}”)
else:
cache.delete(cache_key)
print(f”文章更新,缓存已清除: {instance.title}”)

# 当文章删除前清理相关数据
@receiver(pre_delete, sender=Article)
def cleanup_article_data(sender, instance, **kwargs):
# 清除相关缓存
cache.delete(f’article_{instance.id}’)
# 清除统计缓存
cache.delete(‘popular_articles’)
print(f”文章删除,清理完成: {instance.title}”)

# 监听多对多字段变更
@receiver(m2m_changed, sender=Article.tags.through)
def update_tag_cache(sender, instance, action, **kwargs):
if action in [‘post_add’, ‘post_remove’, ‘post_clear’]:
cache.delete(f’article_tags_{instance.id}’)
print(f”文章标签变更: {instance.title}”)
第二部分:Django高级特性与架构设计
2.1 自定义中间件与请求处理流程控制
中间件是Django提供的强大扩展机制,允许我们在请求处理的不同阶段插入自定义逻辑。高级面试中经常要求手写中间件来解决特定问题。
# 认证中间件:支持多种认证方式
from django.http import JsonResponse
from django.conf import settings
import jwt

class MultiAuthMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
# 优先从Header获取Token
auth_header = request.META.get(‘HTTP_AUTHORIZATION’)
if auth_header and auth_header.startswith(‘Bearer ‘):
token = auth_header.split(‘ ‘)[1]
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[‘HS256’])
request.user_id = payload.get(‘user_id’)
request.auth_type = ‘jwt’
except jwt.InvalidTokenError:
return JsonResponse({‘error’: ‘Invalid token’}, status=401)

# 如果没有JWT,尝试Session认证
elif hasattr(request, ‘user’) and request.user.is_authenticated:
request.auth_type = ‘session’

response = self.get_response(request)

# 在响应头中添加认证信息
if hasattr(request, ‘auth_type’):
response[‘X-Auth-Type’] = request.auth_type

return response

# 限流中间件:防止API滥用
import time
from collections import defaultdict

class RateLimitMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.requests = defaultdict(list)
self.limit = 100 # 每分钟100次
self.window = 60 # 60秒窗口

def __call__(self, request):
client_ip = self.get_client_ip(request)
now = time.time()

# 清理过期记录
self.requests[client_ip] = [
req_time for req_time in self.requests[client_ip]
if now – req_time < self.window ] # 检查是否超限 if len(self.requests[client_ip]) >= self.limit:
return JsonResponse({
‘error’: ‘Rate limit exceeded’,
‘retry_after’: self.window – (now – self.requests[client_ip][0])
}, status=429)

self.requests[client_ip].append(now)
return self.get_response(request)

def get_client_ip(self, request):
x_forwarded_for = request.META.get(‘HTTP_X_FORWARDED_FOR’)
if x_forwarded_for:
return x_forwarded_for.split(‘,’)[0]
return request.META.get(‘REMOTE_ADDR’)
2.2 Django缓存策略与实现
缓存是提升Django应用性能的关键技术,面试中经常考察多级缓存的设计与实现。
# settings.py 缓存配置
CACHES = {
‘default’: {
‘BACKEND’: ‘django.core.cache.backends.redis.RedisCache’,
‘LOCATION’: ‘redis://127.0.0.1:6379/1’,
‘OPTIONS’: {
‘CLIENT_CLASS’: ‘django_redis.client.DefaultClient’,
‘CONNECTION_POOL_KWARGS’: {‘max_connections’: 50},
}
},
‘local’: {
‘BACKEND’: ‘django.core.cache.backends.locmem.LocMemCache’,
‘LOCATION’: ‘unique-snowflake’,
}
}

# 视图缓存装饰器
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key

# 视图级别缓存
@cache_page(60 * 15) # 缓存15分钟
def article_list(request):
articles = Article.objects.select_related(‘author’).filter(status=’published’)
return render(request, ‘articles/list.html’, {‘articles’: articles})

# 模板片段缓存
“””
{% load cache %}
{% cache 500 sidebar user.id %}

{% endcache %}
“””

# 缓存热点数据的函数
def get_popular_articles():
cache_key = ‘popular_articles:v2′
articles = cache.get(cache_key)

if articles is None:
# 查询最近7天阅读量最高的10篇文章
articles = Article.objects.filter(
status=’published’,
created_at__gte=timezone.now() – timedelta(days=7)
).order_by(‘-view_count’)[:10]

# 序列化并缓存
cache.set(cache_key, articles, 3600) # 缓存1小时
print(“从数据库加载热门文章”)
else:
print(“从缓存加载热门文章”)

return articles

# 缓存失效策略
def update_article_view_count(article_id):
article = Article.objects.get(id=article_id)
article.view_count += 1
article.save()

# 清除相关缓存
cache.delete(‘popular_articles:v2′)
cache.delete(f’article_detail_{article_id}’)

# 使用缓存失效模式
cache_key = f’article_{article_id}’
cache.set(cache_key, article, 3600)
2.3 Django REST Framework序列化器深度
DRF是Django生态中最重要的扩展库,序列化器是其核心组件,面试中经常要求手写复杂的序列化器。
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Article, Tag
from django.db import transaction

# 基础序列化器
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [‘id’, ‘username’, ’email’]
read_only_fields = [‘id’]

class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = [‘id’, ‘name’]
read_only_fields = [‘id’]

# 嵌套序列化器与自定义字段
class ArticleDetailSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
tags = TagSerializer(many=True, required=False)
word_count = serializers.SerializerMethodField()
is_recent = serializers.SerializerMethodField()

class Meta:
model = Article
fields = [
‘id’, ‘title’, ‘content’, ‘author’, ‘tags’,
‘status’, ‘created_at’, ‘updated_at’, ‘word_count’, ‘is_recent’
]
read_only_fields = [‘id’, ‘author’, ‘created_at’, ‘updated_at’]

def get_word_count(self, obj):
return len(obj.content) if obj.content else 0

def get_is_recent(self, obj):
from django.utils import timezone
return obj.created_at >= timezone.now() – timezone.timedelta(days=3)

def validate_title(self, value):
if len(value) < 5: raise serializers.ValidationError("标题长度不能少于5个字符") if Article.objects.filter(title=value).exists(): raise serializers.ValidationError("标题已存在") return value def validate(self, data): # 验证文章内容是否包含敏感词 sensitive_words = ['暴力', '色情', '赌博'] content = data.get('content', '') for word in sensitive_words: if word in content: raise serializers.ValidationError({"content": "内容包含敏感词汇"}) return data # 复杂的创建与更新逻辑 class ArticleWriteSerializer(serializers.ModelSerializer): tags = serializers.ListField( child=serializers.CharField(max_length=50), required=False, write_only=True ) class Meta: model = Article fields = ['title', 'content', 'status', 'tags'] @transaction.atomic def create(self, validated_data): tags_data = validated_data.pop('tags', []) request = self.context.get('request') # 创建文章 article = Article.objects.create( author=request.user, **validated_data ) # 处理标签 for tag_name in tags_data: tag, _ = Tag.objects.get_or_create(name=tag_name) article.tags.add(tag) return article @transaction.atomic def update(self, instance, validated_data): tags_data = validated_data.pop('tags', None) # 更新基础字段 for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() # 更新标签 if tags_data is not None: instance.tags.clear() for tag_name in tags_data: tag, _ = Tag.objects.get_or_create(name=tag_name) instance.tags.add(tag) return instance # 视图集使用示例 from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleDetailSerializer # 添加过滤、搜索、排序 filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['status', 'author__username'] search_fields = ['title', 'content'] ordering_fields = ['created_at', 'view_count'] ordering = ['-created_at'] # 自定义动作 @action(detail=True, methods=['post']) def publish(self, request, pk=None): article = self.get_object() if article.status == 'published': return Response({'error': '文章已发布'}, status=status.HTTP_400_BAD_REQUEST) article.status = 'published' article.save() return Response({'status': 'published'}) @action(detail=False, methods=['get']) def hot(self, request): hot_articles = Article.objects.filter( status='published' ).order_by('-view_count')[:5] serializer = self.get_serializer(hot_articles, many=True) return Response(serializer.data) def get_serializer_class(self): if self.action in ['create', 'update', 'partial_update']: return ArticleWriteSerializer return ArticleDetailSerializer def perform_create(self, serializer): serializer.save(author=self.request.user) 第三部分:Django高并发与性能优化实战 3.1 数据库查询优化与索引设计 高并发场景下,数据库往往是性能瓶颈。掌握查询优化和索引设计是高级Django开发者的必备技能。 # 优化前:N+1查询问题 def get_user_articles_v1(user_id): user = User.objects.get(id=user_id) articles = Article.objects.filter(author=user) result = [] for article in articles: # 每次循环都查询数据库 tags = [tag.name for tag in article.tags.all()] result.append({ 'title': article.title, 'tags': tags }) return result # 优化后:使用prefetch_related def get_user_articles_v2(user_id): user = User.objects.get(id=user_id) articles = Article.objects.filter(author=user).prefetch_related('tags') result = [] for article in articles: # 标签已在初始查询中预加载 tags = [tag.name for tag in article.tags.all()] result.append({ 'title': article.title, 'tags': tags }) return result # 使用annotate进行数据库层面的计算 from django.db.models import Count, Q, F, Value from django.db.models.functions import Concat def get_article_stats(): # 统计每个作者的文章数和标签数 stats = User.objects.annotate( article_count=Count('articles', distinct=True), tag_count=Count('articles__tags', distinct=True), # 使用Case进行条件统计 published_count=Count( 'articles', filter=Q(articles__status='published'), distinct=True ) ).values('username', 'article_count', 'tag_count', 'published_count') return list(stats) # 复杂查询示例:查找热门标签 def get_hot_tags(min_articles=3): from django.db.models import Count # 查找至少有3篇文章的标签,并按文章数排序 hot_tags = Tag.objects.annotate( article_count=Count('articles') ).filter( article_count__gte=min_articles ).order_by('-article_count')[:10] return hot_tags # 使用F表达式避免竞态条件 def increment_view_count(article_id): # 安全的计数器增加 Article.objects.filter(id=article_id).update( view_count=F('view_count') + 1 ) 3.2 异步任务与Celery集成 在高并发场景中,耗时操作应该异步化。Celery是Django生态中最流行的分布式任务队列。 # celery.py 配置 from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # tasks.py 定义异步任务 from celery import shared_task from django.core.mail import send_mail from django.core.cache import cache from .models import Article import time @shared_task(bind=True, max_retries=3) def send_article_notification(self, article_id): """发送文章通知任务,带重试机制""" try: article = Article.objects.get(id=article_id) send_mail( f'新文章发布: {article.title}', article.content[:200], 'noreply@example.com', ['subscriber@example.com'], fail_silently=False, ) return f"通知发送成功: {article.title}" except Exception as exc: # 自动重试,指数退避 raise self.retry(exc=exc, countdown=60) @shared_task def batch_update_view_count(article_ids): """批量更新阅读量""" Article.objects.filter(id__in=article_ids).update( view_count=F('view_count') + 1 ) return f"批量更新了{len(article_ids)}篇文章的阅读量" @shared_task def generate_article_report(): """生成每日报告""" from django.utils import timezone from datetime import timedelta yesterday = timezone.now() - timedelta(days=1) published_count = Article.objects.filter( created_at__gte=yesterday, status='published' ).count() # 缓存报告数据 cache.set('daily_report', { 'date': yesterday.strftime('%Y-%m-%d'), 'published_count': published_count, 'generated_at': timezone.now().isoformat() }, 86400) return f"报告生成完成: {published_count}篇文章" # 在视图中调用异步任务 from django.http import JsonResponse from django.views.decorators.http import require_POST @require_POST def publish_article_async(request, article_id): # 立即返回响应,后台处理 send_article_notification.delay(article_id) return JsonResponse({'status': 'queued'}) # 定时任务配置(settings.py) """ CELERY_BEAT_SCHEDULE = { 'generate-daily-report': { 'task': 'myapp.tasks.generate_article_report', 'schedule': crontab(hour=0, minute=0), # 每天午夜 }, 'cleanup-old-cache': { 'task': 'myapp.tasks.cleanup_old_cache', 'schedule': crontab(minute=0), # 每小时 }, } """ 3.3 高并发下的缓存策略 在高并发场景中,缓存是提升性能的关键。我们需要设计合理的缓存策略来应对缓存穿透、缓存击穿和缓存雪崩等问题。 import time import random from django.core.cache import cache from django.db import transaction from django.utils import timezone from datetime import timedelta class CacheManager: """高级缓存管理器""" @staticmethod def get_with_fallback(key, fallback_func, timeout=3600, lock_timeout=10): """ 获取缓存,如果不存在则调用函数计算 防止缓存穿透和击穿 """ # 尝试获取缓存 value = cache.get(key) if value is not None: return value # 获取分布式锁,防止缓存击穿 lock_key = f"{key}:lock" lock_acquired = cache.add(lock_key, True, lock_timeout) if lock_acquired: try: # 再次检查缓存(可能其他进程已设置) value = cache.get(key) if value is not None: return value # 计算新值 value = fallback_func() # 设置缓存,添加随机TTL防止雪崩 actual_timeout = timeout + random.randint(0, 300) cache.set(key, value, actual_timeout) return value finally: cache.delete(lock_key) else: # 等待并重试 time.sleep(0.1) return CacheManager.get_with_fallback(key, fallback_func, timeout, lock_timeout) @staticmethod def get_hot_articles(): """获取热门文章,带缓存保护""" def fetch_hot_articles(): # 模拟耗时查询 time.sleep(0.5) return list(Article.objects.filter( status='published' ).order_by('-view_count')[:10].values('id', 'title', 'view_count')) return CacheManager.get_with_fallback( 'hot_articles:v2', fetch_hot_articles, timeout=1800 # 30分钟 ) # 缓存预热策略 def warmup_cache(): """预热关键缓存""" # 预热热门文章 CacheManager.get_hot_articles() # 预热统计信息 stats_key = 'site_stats' if not cache.get(stats_key): stats = { 'total_articles': Article.objects.count(), 'published_articles': Article.objects.filter(status='published').count(), 'last_update': timezone.now().isoformat() } cache.set(stats_key, stats, 3600) print("缓存预热完成") # 缓存失效策略 def update_article_with_cache_invalidation(article_id, **updates): """更新文章并正确处理缓存失效""" try: with transaction.atomic(): article = Article.objects.select_for_update().get(id=article_id) # 更新字段 for field, value in updates.items(): setattr(article, field, value) article.save() # 清除相关缓存 cache_keys_to_delete = [ f'article_{article_id}', f'article_detail_{article_id}', 'hot_articles:v2', 'site_stats', ] # 批量删除 cache.delete_many(cache_keys_to_delete) # 使用缓存失效模式(Cache-Aside) # 立即设置新值,避免缓存空窗期 cache.set(f'article_{article_id}', article, 3600) return article except Article.DoesNotExist: raise ValueError("文章不存在") # 限流与缓存结合 def check_rate_limit(user_id, action, limit=10, window=60): """检查用户操作频率""" key = f"rate_limit:{user_id}:{action}" current = cache.get(key, 0) if current >= limit:
return False

# 原子性增加
cache.incr(key)
# 设置过期时间(如果第一次)
if current == 0:
cache.expire(key, window)

return True
3.4 数据库连接池与读写分离
高并发下数据库连接是稀缺资源,使用连接池和读写分离可以显著提升性能。
# settings.py 数据库配置(使用django-db-connections)
“””
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.postgresql’,
‘NAME’: ‘mydb’,
‘USER’: ‘myuser’,
‘PASSWORD’: ‘mypassword’,
‘HOST’: ‘master.db.example.com’,
‘PORT’: ‘5432’,
‘CONN_MAX_AGE’: 300, # 连接复用
‘OPTIONS’: {
‘connect_timeout’: 10,
‘options’: ‘-c statement_timeout=30000’ # 30秒超时
}
},
‘replica’: {
‘ENGINE’: ‘django.db.backends.postgresql’,
‘NAME’: ‘mydb’,
‘USER’: ‘myuser’,
‘PASSWORD’: ‘mypassword’,
‘HOST’: ‘replica.db.example.com’,
‘PORT’: ‘5432’,
‘CONN_MAX_AGE’: 300,
}
}
“””

# 数据库路由配置
class PrimaryReplicaRouter:
“””数据库路由:写操作走主库,读操作走从库”””

def db_for_read(self, model, **hints):
# 30%概率走主库,保证数据新鲜度
if random.random() < 0.3: return 'default' return 'replica' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): # 允许跨库关系 db_set = {'default', 'replica'} if obj1._state.db in db_set and obj2._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): # 只在主库执行迁移 return db == 'default' # 在settings中配置 """ DATABASE_ROUTERS = ['myproject.routers.PrimaryReplicaRouter'] """ # 自定义管理器实现读写分离 from django.db import models class ReadWriteManager(models.Manager): def get_queryset(self): # 读操作使用从库 return super().get_queryset().using('replica') def create(self, **kwargs): # 写操作使用主库 return super().create(**kwargs) class ArticleManager(models.Manager): def get_queryset(self): return super().get_queryset().using('replica') def hot_articles(self): return self.get_queryset().filter( status='published' ).order_by('-view_count')[:10] class Article(models.Model): # ... 字段定义 ... objects = ArticleManager() objects_raw = models.Manager() # 原始管理器 # 使用示例 def get_articles(): # 自动使用从库 return Article.objects.hot_articles() def create_article(data): # 自动使用主库 return Article.objects.create(**data) # 手动指定数据库 def manual_db_usage(): # 强制使用主库读取 articles = Article.objects.using('default').filter(status='published') # 强制使用从库写入(不推荐) article = Article(title="Test") article.save(using='replica') 3.5 静态资源优化与CDN集成 前端性能优化也是后端开发者需要关注的领域,特别是静态资源的处理。 # settings.py 静态文件配置 """ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # 使用ManifestStaticFilesStorage进行版本控制 STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' # 媒体文件配置 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') """ # 自定义存储后端(支持CDN) from django.core.files.storage import FileSystemStorage from django.conf import settings class CDNStorage(FileSystemStorage): """支持CDN的文件存储""" def url(self, name): # 如果配置了CDN域名,返回CDN URL if hasattr(settings, 'CDN_DOMAIN'): return f"https://{settings.CDN_DOMAIN}/{name}" return super().url(name) # 在模型中使用 class ArticleImage(models.Model): image = models.ImageField( upload_to='article_images/%Y/%m/', storage=CDNStorage() ) article = models.ForeignKey(Article, on_delete=models.CASCADE) # 视图中处理文件上传 from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse import json @csrf_exempt def upload_image(request): if request.method == 'POST' and request.FILES.get('image'): image = request.FILES['image'] # 验证文件类型和大小 if image.size > 5 * 1024 * 1024: # 5MB
return JsonResponse({‘error’: ‘文件过大’}, status=400)

if not image.name.lower().endswith((‘.png’, ‘.jpg’, ‘.jpeg’, ‘.gif’)):
return JsonResponse({‘error’: ‘不支持的文件类型’}, status=400)

# 保存文件
article_image = ArticleImage(image=image)
article_image.save()

return JsonResponse({
‘url’: article_image.image.url,
‘id’: article_image.id
})

return JsonResponse({‘error’: ‘无效请求’}, status=400)
第四部分:Django高并发实战场景解析
4.1 电商秒杀系统设计
秒杀场景是高并发的经典案例,需要解决超卖问题和请求洪峰。
# models.py 秒杀商品模型
from django.db import models
from django.core.cache import cache
import redis

class SeckillProduct(models.Model):
name = models.CharField(max_length=200)
total_stock = models.IntegerField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
price = models.DecimalField(max_digits=10, decimal_places=2)

@property
def remaining_stock(self):
# 从Redis获取实时库存
r = redis.Redis(host=’localhost’, port=6379, db=0)
stock_key = f”seckill_stock:{self.id}”
return int(r.get(stock_key) or self.total_stock)

def is_active(self):
from django.utils import timezone
now = timezone.now()
return self.start_time <= now <= self.end_time # views.py 秒杀视图 from django.http import JsonResponse from django.db import transaction from django_redis import get_redis_connection import time import uuid def seckill_view(request, product_id): """秒杀接口""" if request.method != 'POST': return JsonResponse({'error': '只支持POST请求'}, status=405) user_id = request.user.id if not user_id: return JsonResponse({'error': '请先登录'}, status=401) try: product = SeckillProduct.objects.get(id=product_id) except SeckillProduct.DoesNotExist: return JsonResponse({'error': '商品不存在'}, status=404) # 检查活动状态 if not product.is_active(): return JsonResponse({'error': '秒杀活动未开始或已结束'}, status=400) # 使用Redis实现分布式锁 lock_key = f"seckill_lock:{product_id}:{user_id}" redis_conn = get_redis_connection('default') # 检查用户是否已参与 if redis_conn.sismember(f"seckill_participants:{product_id}", user_id): return JsonResponse({'error': '您已参与过该秒杀'}, status=400) # 尝试获取锁(防止重复提交) lock_acquired = redis_conn.set(lock_key, '1', nx=True, ex=5) if not lock_acquired: return JsonResponse({'error': '操作过于频繁,请稍后重试'}, status=429) try: # 检查库存(Redis原子操作) stock_key = f"seckill_stock:{product_id}" stock = redis_conn.decr(stock_key) if stock < 0: redis_conn.incr(stock_key) # 回滚 return JsonResponse({'error': '商品已售罄'}, status=400) # 创建订单(数据库事务) with transaction.atomic(): order = Order.objects.create( user=request.user, product=product, quantity=1, price=product.price, status='paid' ) # 记录参与用户 redis_conn.sadd(f"seckill_participants:{product_id}", user_id) # 发送异步通知 send_order_notification.delay(order.id) return JsonResponse({ 'success': True, 'order_id': order.id, 'message': '秒杀成功!' }) except Exception as e: # 异常时恢复库存 redis_conn.incr(stock_key) return JsonResponse({'error': f'秒杀失败: {str(e)}'}, status=500) finally: # 释放锁 redis_conn.delete(lock_key) # 定时任务:同步Redis库存到数据库 from celery import shared_task @shared_task def sync_seckill_stock(): """每分钟同步一次库存""" products = SeckillProduct.objects.filter( start_time__lte=timezone.now(), end_time__gte=timezone.now() ) redis_conn = get_redis_connection('default') for product in products: stock_key = f"seckill_stock:{product.id}" current_stock = redis_conn.get(stock_key) if current_stock is not None: # 更新数据库 SeckillProduct.objects.filter(id=product.id).update( total_stock=int(current_stock) ) # 队列处理:订单创建 @shared_task def process_seckill_order(order_id): """后台处理秒杀订单""" try: order = Order.objects.get(id=order_id) # 发送短信通知 send_sms.delay(order.user.phone, f"秒杀成功!订单号: {order.order_number}") # 记录日志 logger.info(f"秒杀订单处理完成: {order_id}") except Exception as e: logger.error(f"订单处理失败: {order_id}, error: {e}") 4.2 高并发文章阅读系统 文章阅读系统需要处理大量的读请求,重点在于缓存策略和数据库优化。 # views.py 文章详情页 from django.shortcuts import get_object_or_404 from django.http import JsonResponse, HttpResponse from django.views.decorators.cache import cache_page from django.core.cache import cache from django.utils import timezone from datetime import timedelta import time # 1. 基础缓存版本 @cache_page(60 * 5) # 5分钟缓存 def article_detail_v1(request, article_id): article = get_object_or_404(Article, id=article_id, status='published') # 更新阅读量(每次都会执行) article.view_count += 1 article.save() return JsonResponse({ 'id': article.id, 'title': article.title, 'content': article.content, 'view_count': article.view_count, 'author': article.author.username }) # 2. 高性能版本:缓存 + 异步更新 def article_detail_v2(request, article_id): cache_key = f'article_detail:{article_id}' # 尝试从缓存获取 cached_data = cache.get(cache_key) if cached_data: # 异步更新阅读量 increment_view_count_async.delay(article_id) return JsonResponse(cached_data) # 缓存未命中,查询数据库 article = get_object_or_404(Article, id=article_id, status='published') # 序列化数据 data = { 'id': article.id, 'title': article.title, 'content': article.content, 'view_count': article.view_count, 'author': article.author.username, 'tags': [tag.name for tag in article.tags.all()] } # 设置缓存(添加随机TTL避免雪崩) ttl = 300 + random.randint(0, 60) cache.set(cache_key, data, ttl) # 异步更新阅读量 increment_view_count_async.delay(article_id) return JsonResponse(data) # 3. 阅读量异步更新 from celery import shared_task @shared_task def increment_view_count_async(article_id): """异步更新阅读量""" # 使用Redis计数器 redis_conn = get_redis_connection('default') key = f'article_views:{article_id}' redis_conn.incr(key) # 定时同步到数据库(避免频繁写) if random.random() < 0.1: # 10%概率同步 views = int(redis_conn.get(key) or 0) Article.objects.filter(id=article_id).update(view_count=F('view_count') + views) redis_conn.delete(key) # 4. 热点文章缓存预热 def hot_articles_cache(): """热点文章缓存""" hot_ids = cache.get('hot_article_ids') if not hot_ids: # 从数据库获取热点文章ID hot_ids = list(Article.objects.filter( status='published', created_at__gte=timezone.now() - timedelta(days=7) ).order_by('-view_count')[:20].values_list('id', flat=True)) cache.set('hot_article_ids', hot_ids, 3600) # 预热这些文章的缓存 for article_id in hot_ids: cache_key = f'article_detail:{article_id}' if not cache.get(cache_key): try: article = Article.objects.select_related('author').prefetch_related('tags').get(id=article_id) data = { 'id': article.id, 'title': article.title, 'content': article.content, 'view_count': article.view_count, 'author': article.author.username, 'tags': [tag.name for tag in article.tags.all()] } cache.set(cache_key, data, 1800) # 30分钟 except Article.DoesNotExist: pass # 5. 限流保护 from django.core.cache import cache import time def rate_limit_check(user_id, article_id): """检查用户阅读频率""" key = f'user_read_limit:{user_id}:{article_id}' current = cache.get(key, 0) # 限制每分钟最多阅读5篇文章 if current >= 5:
return False

cache.set(key, current + 1, 60)
return True

def article_detail_with_limit(request, article_id):
user_id = request.user.id if request.user.is_authenticated else None

if user_id and not rate_limit_check(user_id, article_id):
return JsonResponse({‘error’: ‘阅读频率过高,请稍后再试’}, status=429)

return article_detail_v2(request, article_id)
4.3 实时统计与监控
高并发系统需要实时监控,以便及时发现问题并调整策略。
# models.py 统计模型
from django.db import models
from django.contrib.postgres.fields import JSONField
from django.utils import timezone

class SystemMetrics(models.Model):
“””系统指标记录”””
timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
metric_type = models.CharField(max_length=50, db_index=True)
value = models.FloatField()
tags = JSONField(default=dict)

class Meta:
indexes = [
models.Index(fields=[‘metric_type’, ‘timestamp’]),
]

# views.py 监控接口
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import psutil
import time

@require_http_methods([“GET”])
def system_metrics(request):
“””获取系统实时指标”””
# CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)

# 内存使用率
memory = psutil.virtual_memory()
memory_percent = memory.percent

# 磁盘使用率
disk = psutil.disk_usage(‘/’)
disk_percent = disk.percent

# 网络IO
net_io = psutil.net_io_counters()

# 数据库连接数(PostgreSQL)
from django.db import connection
with connection.cursor() as cursor:
cursor.execute(“SELECT count(*) FROM pg_stat_activity WHERE state = ‘active’”)
db_connections = cursor.fetchone()[0]

# Redis连接数
try:
redis_conn = get_redis_connection(‘default’)
redis_info = redis_conn.info(‘clients’)
redis_connections = redis_info[‘connected_clients’]
except:
redis_connections = 0

# 保存到数据库
metrics_data = [
{‘type’: ‘cpu’, ‘value’: cpu_percent},
{‘type’: ‘memory’, ‘value’: memory_percent},
{‘type’: ‘disk’, ‘value’: disk_percent},
{‘type’: ‘db_connections’, ‘value’: db_connections},
{‘type’: ‘redis_connections’, ‘value’: redis_connections},
]

for metric in metrics_data:
SystemMetrics.objects.create(
metric_type=metric[‘type’],
value=metric[‘value’],
tags={‘host’: request.get_host()}
)

return JsonResponse({
‘timestamp’: time.time(),
‘cpu’: cpu_percent,
‘memory’: memory_percent,
‘disk’: disk_percent,
‘db_connections’: db_connections,
‘redis_connections’: redis_connections,
‘network’: {
‘bytes_sent’: net_io.bytes_sent,
‘bytes_recv’: net_io.bytes_recv,
}
})

# 业务指标统计
from django.db.models import Count, Avg
from django.utils import timezone
from datetime import timedelta

def business_metrics():
“””业务指标统计”””
now = timezone.now()
last_hour = now – timedelta(hours=1)
last_day = now – timedelta(days=1)

# 1小时内的注册用户数
new_users = User.objects.filter(
date_joined__gte=last_hour
).count()

# 1小时内的文章发布数
new_articles = Article.objects.filter(
created_at__gte=last_hour
).count()

# 24小时内的活跃用户数(有操作的用户)
active_users = Article.objects.filter(
created_at__gte=last_day
).values(‘author’).distinct().count()

# 平均响应时间(从日志分析)
# 这里简化为从缓存获取
avg_response_time = cache.get(‘avg_response_time’, 0)

# 错误率
total_requests = cache.get(‘total_requests’, 1)
error_requests = cache.get(‘error_requests’, 0)
error_rate = (error_requests / total_requests * 100) if total_requests > 0 else 0

return {
‘new_users’: new_users,
‘new_articles’: new_articles,
‘active_users’: active_users,
‘avg_response_time’: avg_response_time,
‘error_rate’: round(error_rate, 2),
‘timestamp’: now.isoformat()
}

# 自定义中间件:记录请求指标
class MetricsMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
start_time = time.time()

response = self.get_response(request)

duration = time.time() – start_time

# 记录响应时间
cache_key = ‘response_times’
response_times = cache.get(cache_key, [])
response_times.append(duration)
if len(response_times) > 1000:
response_times = response_times[-1000:]
cache.set(cache_key, response_times, 3600)

# 计算平均响应时间
if response_times:
avg_time = sum(response_times) / len(response_times)
cache.set(‘avg_response_time’, avg_time, 3600)

# 记录请求总数和错误数
total_key = ‘total_requests’
error_key = ‘error_requests’

cache.incr(total_key)
if response.status_code >= 400:
cache.incr(error_key)

# 设置过期时间
cache.expire(total_key, 3600)
cache.expire(error_key, 3600)

response[‘X-Response-Time’] = f”{duration:.4f}s”
return response
4.4 微服务化与API网关
随着系统规模扩大,Django应用需要向微服务架构演进。
# 服务注册与发现(使用Redis)
class ServiceRegistry:
“””服务注册中心”””

def __init__(self):
self.redis = get_redis_connection(‘default’)
self.service_key = ‘service_registry’
self.heartbeat_interval = 30

def register(self, service_name, host, port, metadata=None):
“””注册服务实例”””
instance_id = f”{service_name}:{host}:{port}:{int(time.time())}”
service_info = {
‘instance_id’: instance_id,
‘service_name’: service_name,
‘host’: host,
‘port’: port,
‘metadata’: metadata or {},
‘last_heartbeat’: int(time.time())
}

# 存储服务信息
self.redis.hset(self.service_key, instance_id, str(service_info))
# 设置过期时间
self.redis.expire(self.service_key, self.heartbeat_interval * 2)

return instance_id

def deregister(self, instance_id):
“””注销服务”””
self.redis.hdel(self.service_key, instance_id)

def discover(self, service_name):
“””发现服务”””
services = self.redis.hgetall(self.service_key)
result = []

for instance_id, info in services.items():
service_info = eval(info) # 注意:生产环境应使用JSON
if service_info[‘service_name’] == service_name:
# 检查是否过期
if int(time.time()) – service_info[‘last_heartbeat’] < self.heartbeat_interval * 2: result.append(service_info) return result def heartbeat(self, instance_id): """心跳更新""" info = self.redis.hget(self.service_key, instance_id) if info: service_info = eval(info) service_info['last_heartbeat'] = int(time.time()) self.redis.hset(self.service_key, instance_id, str(service_info)) # API网关示例 import requests from django.http import JsonResponse class APIGateway: """简单的API网关""" def __init__(self): self.registry = ServiceRegistry() def route_request(self, service_name, path, request): """路由请求到对应服务""" # 发现服务 instances = self.registry.discover(service_name) if not instances: return JsonResponse({'error': f'Service {service_name} not available'}, status=503) # 负载均衡(简单轮询) instance = instances[int(time.time()) % len(instances)] # 构建目标URL target_url = f"http://{instance['host']}:{instance['port']}{path}" # 转发请求 try: response = requests.request( method=request.method, url=target_url, headers=dict(request.headers), data=request.body, timeout=5 ) return JsonResponse( response.json(), status=response.status_code, headers={'X-Proxy-From': instance['instance_id']} ) except requests.RequestException as e: return JsonResponse({'error': str(e)}, status=502) # 服务端示例:用户服务 from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def user_service(request): """用户服务接口""" if request.method == 'GET': user_id = request.GET.get('id') try: user = User.objects.get(id=user_id) return JsonResponse({ 'id': user.id, 'username': user.username, 'email': user.email }) except User.DoesNotExist: return JsonResponse({'error': 'User not found'}, status=404) elif request.method == 'POST': data = json.loads(request.body) user = User.objects.create_user( username=data['username'], email=data['email'], password=data['password'] ) return JsonResponse({'id': user.id, 'username': user.username}, status=201) # 服务注册启动脚本 def register_user_service(): """注册用户服务""" registry = ServiceRegistry() instance_id = registry.register( service_name='user-service', host='127.0.0.1', port=8001, metadata={'version': '1.0', 'region': 'us-east-1'} ) # 启动心跳线程 import threading def send_heartbeat(): while True: registry.heartbeat(instance_id) time.sleep(20) threading.Thread(target=send_heartbeat, daemon=True).start() return instance_id 第五部分:Django面试常见问题与答案 5.1 基础概念类问题 Q1: Django的ORM如何避免N+1查询问题? A: N+1查询问题是由于在循环中访问关联对象导致的。解决方案包括: 使用 select_related() 处理外键和一对一关系 使用 prefetch_related() 处理多对多和一对多关系 使用 only() 和 defer() 减少查询字段 使用 values() 和 values_list() 进行优化 # 错误示例 articles = Article.objects.all() for article in articles: print(article.author.username) # 每次循环都查询作者 # 正确示例 articles = Article.objects.select_related('author').all() for article in articles: print(article.author.username) # 作者已预加载 Q2: Django中间件的执行顺序是怎样的? A: 中间件按照settings.py中MIDDLEWARE列表的顺序执行: process_request : 从上到下 process_view : 从上到下 视图函数执行 process_exception : 从下到上(如果发生异常) process_response : 从下到上 5.2 性能优化类问题 Q3: 如何优化Django Admin的性能? A: 在ModelAdmin中设置 list_select_related 使用 autocomplete_fields 重写 get_queryset 方法优化查询 添加合适的数据库索引 使用 list_prefetch_related class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created_at'] list_filter = ['status', 'created_at'] search_fields = ['title', 'content'] list_select_related = ['author'] list_prefetch_related = ['tags'] def get_queryset(self, request): return super().get_queryset(request).filter( status__in=['draft', 'published'] ) Q4: Django的缓存机制有哪些?如何选择? A: Django提供多种缓存后端: 内存缓存 :适合开发环境 文件系统缓存 :适合单服务器 Redis缓存 :生产环境首选,支持分布式 数据库缓存 :适合已有数据库的场景 选择策略: 小型应用:内存或文件缓存 中型应用:Redis单实例 大型应用:Redis集群 超大规模:多级缓存(本地+Redis) 5.3 架构设计类问题 Q5: 如何设计一个支持百万用户的Django应用? A: 需要多层架构设计: 负载均衡 :Nginx + Gunicorn/UWSGI 数据库 :主从复制 + 读写分离 缓存 :Redis集群 异步任务 :Celery + RabbitMQ/Redis 静态文件 :CDN加速 监控 :Prometheus + Grafana 日志 :ELK Stack Q6: Django的信号机制有什么优缺点? A: 优点: 解耦:发送者不需要知道接收者 灵活性:可以动态连接/断开信号 内置:Django原生支持 缺点: 难以调试:信号流不直观 性能影响:同步信号会阻塞请求 顺序问题:信号执行顺序不确定 5.4 高并发实战类问题 Q7: 如何实现一个秒杀系统防止超卖? A: 核心思路: 库存预热 :将库存加载到Redis 原子扣减 :使用Redis的DECR原子操作 分布式锁 :防止同一用户重复提交 队列削峰 :异步创建订单 数据库事务 :保证最终一致性 Q8: 如何处理缓存雪崩、穿透、击穿? A: 雪崩 :大量缓存同时失效 解决:随机过期时间、热点数据永不过期 穿透 :查询不存在的数据 解决:布隆过滤器、缓存空对象 击穿 :热点数据失效瞬间大量请求 解决:互斥锁、逻辑过期 第六部分:Django面试实战技巧 6.1 面试准备清单 技术栈准备: Django核心机制(ORM、中间件、信号) DRF序列化器与视图集 数据库优化(索引、查询优化) 缓存策略(Redis、Memcached) 异步任务(Celery) 部署与运维(Docker、Nginx、Gunicorn) 项目经验准备: 准备2-3个完整的Django项目 能够清晰描述项目架构 熟悉遇到的性能问题及解决方案 了解项目的部署流程 代码能力准备: 手写ORM查询 自定义中间件 设计序列化器 实现缓存策略 6.2 面试回答技巧 1. 结构化回答: 使用STAR法则(Situation, Task, Action, Result)描述项目经验。 2. 展示深度: 不仅回答”怎么做”,还要解释”为什么这么做”。 3. 主动扩展: 回答完问题后,主动提及相关的优化点或最佳实践。 4. 诚实面对: 遇到不会的问题,诚实承认并尝试给出思路,而不是胡编乱造。 6.3 常见陷阱与注意事项 陷阱1:过度设计 不要在小项目中使用微服务架构 根据实际需求选择技术方案 陷阱2:忽视测试 Django单元测试非常重要 面试中可能要求写测试用例 陷阱3:安全意识不足 SQL注入、XSS攻击的防护 敏感信息不要硬编码 结语 Django面试在2024年更加注重实战能力和架构思维。从基础的ORM使用到高并发场景下的性能优化,每个环节都需要深入理解。建议求职者: 夯实基础 :深入理解Django核心机制 实践驱动 :通过实际项目积累经验 持续学习 :关注Django新特性和社区最佳实践 系统思维 :从整体架构角度思考问题 记住,面试不仅是技术的展示,更是解决问题能力的体现。希望本文能帮助你在Django面试中脱颖而出,成功拿到心仪的offer!