django開發系列:視圖高級之限制請求method裝飾器
常用的請求method
GET請求: 一般用來向服務器索取數據,但是不會向服務器提交數據,不會對服務器的狀態進行更改。
POST請求:一般是用來向 服務器提交數據,會對服務器的狀態進行更改。
限制請求裝飾器
Django內置的視圖裝飾器可以給視圖提供一些限制。比如限制某個視圖只能通過GET
的method訪問等。以下是一些常用的內置視圖裝飾器。
django.views.decorators.http.require_http_methods
:這個裝飾器需要傳遞一個允許訪問的方法的列表。比如只能通過GET的方式訪問。那麼示例代碼如下:
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def index(request):
pass
django.views.decorators.http.require_GET
:這個裝飾器相當於是require_http_methods([‘GET’])的簡寫形式,只允許使用GET的method來訪問視圖。示例代碼如下:
@require_GET
def index(request):
# 首頁返回所有的文章
# 只能使用GET請求來訪問這個視圖函數
articles = Article.objects.all()
return render(request,'index.html',context={"articles":articles})
django.views.decorators.http.require_POST
:這個裝飾器相當於是require_http_methods([‘POST’])的簡寫形式,只允許使用POST的method來訪問視圖。示例代碼如下:
from django.views.decorators.http import require_POST
@require_POST
def add_article(request):
title = request.POST.get("title")
content = request.POST.get('content')
Article.objects.create(title=title,content=content)
return HttpResponse('success')
django.views.decorators.http.require_safe
:這個裝飾器相當於是require_http_methods([‘GET’,‘HEAD’])的簡寫形式,只允許使用相對安全的方式來訪問視圖。因爲GET和HEAD不會對服務器產生增刪改的行爲。因此是一種相對安全的請求方式。示例代碼如下:
from django.views.decorators.http import require_safe
@require_safe
def index(request):
pass
- 可以使用裝飾器限制請求類型,並且利用已有的類型進行各自操作
from django.shortcuts import render
from .models import Article
from django.views.decorators.http import require_http_methods,require_GET,require_POST,require_safe
from django.http import HttpResponse
@require_http_methods(['POST','GET'])
def add_article(request):
# 如果使用GET請求來訪問這個視圖函數,那麼就返回一個添加文章的HTML頁面
# 如果使用POST請求來訪問這個視圖函數,那麼就獲取提交上來的數據,然後保存
# 到數據庫中
if request.method == 'GET':
return render(request,'add_article.html')
else:
title = request.POST.get("title")
content = request.POST.get('content')
Article.objects.create(title=title,content=content)
return HttpResponse('success')