django view 装饰器

Django提供了几个可以应用于视图以支持各种HTTP特性的装饰器

Allowed HTTP

django.views.decorators.http里的装饰器可以根据请求方法限制对视图的访问。

require_http_methods

接收特定的HTPP 请求方法

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()请求

Conditional view processing

以下django.view .decorators.http中的decorator可用于控制特定视图上的缓存行为。

condition(etag_func=None, last_modified_func=None)

etag(etag_func)

last_modified(last_modified_func)

def latest_entry(request, blog_id):
    return Entry.objects.filter(blog=blog_id).latest("published").published

from django.views.decorators.http import condition

@condition(last_modified_func=latest_entry)
def front_page(request, blog_id):
    ...

GZip compression

django.view .decorators.gzip中的decorator在每个视图的基础上控制了内容压缩。

gzip_page()

如果浏览器允许gzip压缩,则此装饰器将压缩内容。它相应地设置了Vary标头,以便缓存将其存储基于accept编码标头。

Vary headers

vary中的decorator可用于根据特定的请求头控制缓存。

vary_on_cookie(func)

vary_on_headers(*headers)

不同的标头定义了缓存机制在构建缓存键时应该考虑哪些请求标头。

Caching

django.views.decorators.cache 控制服务端和客户端缓存中的decorator。

cache_control(**kwargs)

这个装饰器通过添加所有关键字参数来修复响应的Cache-Control报头。

never_cache(view_func)

这个修饰符向响应添加了Cache-Control: max-age=0、no-cache、no-store、must-revalidate头,以指示永远不应该缓存页面。

posted @ 2018-10-02 12:57  Super-Yan  阅读(505)  评论(0编辑  收藏  举报