django1.8 view(5): view decorators

本文翻译自django1.8.2官方文档中The view layer的Decorators部分

View decorators

django提供了多种装饰器,视图能使用,来支持多种HTTP特性.

Allowed HTTP methods

django.views.decorators.http中的装饰器能通过请求方法来限制view的连接.如果条件不成立,这些装饰器会返回一个django.http.HttpResponseNotAllowed对象.
- required_http_method(request_method_list)
装饰要求,view只能接收特定的请求方法,使用示例:

from django.views.decotors.http import require_http_methods

@required_http_methods(['GET', 'POST'])
def my_view(request):
    # 现在能假设,只有GET或POST请求能到这
    # ...
    pass

注意:请求方法必须大写

  • require_GET()
    装饰器要求,视图只接受GET请求

  • require_POST()
    装饰器要求,视图只接受POST请求

  • require_safe()
    装饰器要求,视图只接受GET和HEAD请求.这些方法通常情况下被认为是’安全’的,因为它们通常是请求资源,而不是请求一个行为(taking an action).
    注意:

    Django will automatically strip the content of responses to HEAD requests while leaving the headers unchanged,
    所以你得在视图里自己处理HEAD请求,就像处理GET请求一样.因为一些软件,就像link checkers,依赖HEAD请求,所以你最好使用required_safe而不是require_GET.

Conditional view processing

下面的在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 compressio

django.views.decorators.gzip中的这些装饰器能控制每个view的压缩.
- gzip_page()
这个装饰器会压缩内容如果浏览器允许gzip压缩.它设置了多种头,以便能基于Accept-Encoding头里的设置来缓存.

Vary headers

django.views.decorators.vary里的装饰器能根据请求头来控制缓存.
- vary_on_cookie(func)
- vary_on_headers(*headers)
The Vary header defines which request headers a cache mechanism should take into account when building its cache key.
详情请看using vary headers.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值