一、认证与权限类
1. @login_required
-
功能:强制用户登录访问
-
参数:
login_url
:未登录跳转路径(默认:settings.LOGIN_URL
)redirect_field_name
:重定向字段名(默认:‘next’)
-
示例:
from django.contrib.auth.decorators import login_required @login_required(login_url='/custom-login/') def profile_view(request): return render(request, 'profile.html')
-
场景:
- 用户个人中心
- 订单管理页面
- 需要登录才能访问的API端点
-
注意:类视图使用时需配合
method_decorator
2. @permission_required
- 功能:检查用户权限
- 参数:
perm
:权限字符串或列表(必需)login_url
:无权限跳转路径raise_exception
:是否抛出403异常(默认False)
- 示例:
from django.contrib.auth.decorators import permission_required @permission_required('polls.change_question', login_url='/admin/') def edit_question(request, pk): # 编辑问题逻辑
- 场景:
- 后台管理系统
- 多角色权限控制
- 敏感操作接口
二、请求处理类
3. @require_http_methods
- 功能:限制请求方法
- 参数:
methods
:允许的方法列表(如["GET", "POST"]
)
- 示例:
from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "HEAD"]) def article_detail(request, pk): # 仅允许GET/HEAD请求
- 场景:
- RESTful API端点
- 防止GET表单提交
- 安全敏感操作
4. @condition
- 功能:条件请求处理(ETag/Last-Modified)
- 参数:
etag_func
:生成ETag的函数last_modified_func
:生成最后修改时间的函数
- 示例:
from django.views.decorators.http import condition def get_last_modified(request, *args, **kwargs): return Article.objects.get(pk=kwargs['pk']).updated_at @condition(last_modified_func=get_last_modified) def article_detail(request, pk): # 实现条件GET请求
- 场景:
- 内容协商
- 大文件下载
- 高频访问的静态资源
三、缓存类
5. @cache_page
- 功能:页面级缓存
- 参数:
timeout
:缓存时间(秒,必需)cache
:使用的缓存配置(默认:default
)key_prefix
:缓存键前缀
- 示例:
from django.views.decorators.cache import cache_page @cache_page(60 * 15, cache='special_cache') def product_list(request): # 缓存15分钟
- 场景:
- 商品列表页
- 新闻聚合页
- 变化频率低的页面
- 注意:在类视图中必须使用
method_decorator
四、安全类
6. @csrf_exempt
-
功能:禁用
CSRF
保护 -
参数:无
-
示例:
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def webhook_receiver(request): # 接收第三方Webhook
-
场景:
- 跨域API端点
- 第三方服务回调
- 遗留系统接口
-
警告:仅在绝对必要时使用!
7. @ensure_csrf_cookie
- 功能:确保返回
CSRF Cookie
- 参数:无
- 示例:
from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def login_form(request): # 登录表单页面
- 场景:
- 前后端分离项目的登录页
- 需要
CSRF
保护的AJAX
请求 - 混合传统表单和
AJAX
的页面
五、第三方扩展
8. @ratelimit(django-ratelimit)
- 功能:请求频率限制
- 参数:
key
:限制维度(‘ip’/‘user’/‘header:xxx’)rate
:限制频率(如’10/m’)method
:限制的HTTP方法block
:是否直接阻塞请求(默认False)
- 示例:
from django_ratelimit.decorators import ratelimit @ratelimit(key='user', rate='5/m', block=True) def comment_create(request): # 限速的评论提交
- 场景:
- 防止暴力破解
- API速率限制
- 资源保护
六、高级用法
装饰器组合
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
@login_required
@cache_page(60 * 5)
def dashboard(request):
# 登录用户才能访问的缓存仪表盘
执行顺序:从下往上执行(最后的装饰器最先执行)
七、类视图装饰指南
方法装饰
from django.utils.decorators import method_decorator
@method_decorator(login_required, name='dispatch')
class ProfileView(View):
# 整个视图需要登录
特定方法装饰
class ProductView(View):
@method_decorator(cache_page(60 * 60))
def get(self, request):
# 缓存GET请求
@method_decorator(permission_required('shop.add_product'))
def post(self, request):
# 需要权限的POST
总结对比表
装饰器 | 最佳场景 | 性能影响 | 安全等级 |
---|---|---|---|
login_required | 用户个人相关页面 | 低 | 高 |
cache_page | 高并发只读页面 | 极高 | 中 |
require_http_methods | REST API设计 | 无 | 高 |
ratelimit | 登录/注册等表单页 | 中 | 极高 |
ensure_csrf_cookie | 前后端分离认证 | 低 | 高 |