视图装饰器¶
Django 提供很多装饰器,它们可以为视图支持多种 HTTP 特性。
查看 装饰类 来了解如何在基于类的视图中使用这些装饰器。
允许的 HTTP 方法¶
在 django.views.decorators.http 中的装饰器可以用来根据请求方法来限制对视图的访问。如果条件不满足,这些装饰器将返回 django.http.HttpResponseNotAllowed 。
-
require_http_methods(request_method_list)¶ 装饰器可以要求视图只接受特定的请求方法。用法如下:
from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... pass
注意请求方法应该是大写。
-
require_GET()¶ 装饰器可以要求视图只接受 GET 方法。用法如下:
-
require_POST()¶ 装饰器可以要求视图只接受 POST 方法。用法如下:
-
require_safe()¶ 装饰器可以要求视图只接收 GET 和 HEAD 方法。这些方法通常被认为是安全的,因为它们除了检索请求的资源外,没有特别的操作。
注解
Web 服务器自动删除对 HEAD 请求的相应内容,并保持头部不变,所以你可以像处理视图里的 GET 请求一样处理 HEAD 请求。因为一些软件依赖 HEAD 请求(比如链接检测器),因此你需要使用
require_safe而不是require_GET。
条件视图处理¶
下面 django.views.decorators.http 的装饰器被用来控制特殊视图中的缓存行为。
-
condition(etag_func=None, last_modified_func=None)¶
-
etag(etag_func)¶
-
last_modified(last_modified_func)¶ 这些装饰器被用来生成
ETag和Last-Modified头部;查看 conditional view processing 。
GZip 压缩¶
django.views.decorators.gzip 里的装饰器控制基于每个视图的内容压缩。
-
gzip_page()¶ 如果浏览器允许 gzip 压缩,那么这个装饰器将压缩内容。它相应的设置了
Vary头部,这样缓存将基于Accept-Encoding头进行存储。
Vary 头¶
django.views.decorators.vary 里的装饰器被用来根据特殊请求头的缓存控制。
-
vary_on_headers(*headers)¶ Vary头定义了缓存机制在构建其缓存密钥时应该考虑哪些请求报头。查看 using vary headers 。
缓存¶
django.views.decorators.cache 中的装饰器控制服务器及客户端的缓存。
-
cache_control(**kwargs)¶ 这个装饰器通过添加所有关键字参数来修补响应的
Cache-Control头。查看patch_cache_control()来了解转换的详情。
-
never_cache(view_func)¶ 这个装饰器添加
Cache-Control: max-age=0, no-cache, no-store, must-revalidate头到一个响应来标识禁止缓存该页面。
Common¶
The decorators in django.views.decorators.common allow per-view
customization of CommonMiddleware behavior.
-
no_append_slash()¶ This decorator allows individual views to be excluded from
APPEND_SLASHURL normalization.