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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章