django中三種判斷請求類型的方法


1.面向對象方法

在views.py中編寫

  1. 引入模塊
from django import views
  1. 函數編寫,創建類文件
class View(views.View):
    def get(self, request):
        print('GET方法')
        return HttpResponse('GET方法')
        
    def post(self, request):
        print('POST方法')
        return HttpResponse('POST方法')

  1. 配置路由 urls.py中編寫
  • 引入模塊
from django.views.generic import TemplateView
  • 配置路由
    yyy方法可以讓我們不用在views.py中編寫函數,直接就可以通過訪問yyy方法訪問2.html文件
urlpatterns = [
    path('xxx', views.View.as_view()),
    path('yyy', TemplateView.as_view(template_name='kanyun/2.html'))
]

使用

前端頁面,點擊發送,表單提交地址為,路由中的xxx,如果是post請求則返回post函數中的結果,如果是get請求則返回get函數中的結果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/kanyun/xxx" method="post">
    {%csrf_token%}
    <button type="submit">發送</button>
</form>
</body>
</html>

2.裝飾器修飾法

  • 引入模塊
from django.views.decorators.http import require_GET, require_http_methods, require_POST
  • 函數編寫
# 只能接收get的請求,如果是post請求訪問則直接報錯,無法接收
@require_GET
def rgt(request):
    return HttpResponse('GET請求')

# 只能接收post的請求,如果是get請求訪問則直接報錯,無法接收
@require_POST
def rpt(request):
    return HttpResponse('POST請求')
# 可以接收到列表中的規定的請求,列表中的情愛u方法必須大寫 
@require_http_methods(['GET', 'POST'])
def gpt(request):
    return HttpResponse('收到')
    

3.通過request.method判斷

def check(request):
    if request.method == 'POST':
        return HttpResponse('我是post請求')
    elif request.method == 'GET':
        return HttpResponse('我是get請求')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM