HTTP1.0中: GET、POST ,HEAD方法。
HTTP2.0中: GET、POST,HEAD, OPTIONS、PUT、PATCH、DELETE、TRACE 等方法。
其实我们最常用的就是GET,POST
Django内置的视图装饰器可以给视图提供一些限制。比如这个视图只能通过GET的method访问等。
(1)django.http.decorators.http.require_http_methods
from django.views.decorators.http import require_http_methods
@require_http_methods([‘GET‘])
def index(request):
# 首页返回所有文章
articles = Article.objects.all()
return render(request, ‘k01_method_demo/index.html‘, context={"articles": articles})
如果发送post请求,浏览器将报405错误
(2)django.views.decorators.http.require_GET
from django.views.decorators.http import require_GET
@require_GET
def index(request):
# 首页返回所有文章
articles = Article.objects.all()
return render(request, ‘k01_method_demo/index.html‘, context={"articles": articles})
如果发送post请求,浏览器将报405错误
@require_GET = @require_http_methods([‘GET‘]) 结果相同
(3)django.views.decorators.http.require_POST
from django.views.decorators.http import require_POST
@require_POST
def add_article(request):
title = request.POST.get("title")
content = request.POST.get("content")
price = request.POST.get("price")
Article.objects.create(title=title, content=content, price=price)
return HttpResponse("成功")
@require_POST = @require_http_methods([‘POST‘]) 结果相同
(4)django.views.decorators.http.require_safe
from django.views.decorators.http import require_GET
@require_safe
def index(request):
# 首页返回所有文章
articles = Article.objects.all()
return render(request, ‘k01_method_demo/index.html‘, context={"articles": articles})
@require_safe = @require_http_methods([‘GET‘,‘HEAD‘]) 结果相同
原文:https://blog.51cto.com/jiajinh/2434406