1、path位置傳遞,注意:參數名必須一致,浪費了我太多時間
url.py中:
path('info/<p1>/<p2>/', Tinfo.as_view())
path('info/<str:p1>/<int:p2>/', Tinfo.as_view()) # 這么寫也可以
views.py中:
class Tinfo(APIView): def get(self, request, p1, p2): print('參數是:', p1) return Response('success:{},{}'.format(p1, p2))
瀏覽器中輸入:
127.0.0.1:8000/badmin/info/pkfkfkf/123/
2、re_path,這個與之前的傳遞方式已經不同了,這個就沒有參數名需要一致的問題了,根據參數位置自動匹配
url.py中
from django.urls import re_path re_path('info/(\w+)/(\d+)/', Tinfo.as_view()),
view.py中
class Tinfo(APIView): def get(self, request, p1, p2): print('參數是:', p1) return Response('success:{},{}'.format(p1, p2))
3、關鍵字傳參
path('info',Tinfo.as_view()) # 推薦這種方法:url地址這樣寫/info?p1=123,獲取數據用request.GET.get('p1')
path('info/<str:p1>/<int:p2>/', Tinfo.as_view()) #與上同
GET:
class Tinfo(APIView): def get(self, request): p3 = request.GET.get('p3') return Response('success:{}'.format(p3))
瀏覽器中輸入:
127.0.0.1:8000/badmin/info/pkfkfkf/123/?p3=err
POST取參數:
url.py:
path('info/<str:p1>/<int:p2>/', Tinfo.as_view()) # 與上相同
views.py中:
class Tinfo(APIView): def post(self, request, p1, p2): p4 = request.POST.get('p4') print('另一種參數p4:', p4) return Response('success:{},{}'.format(p1, p2))
瀏覽器輸入:
以上幾種方法包含了常用的參數傳遞方式,如果覺得寫得好,請支持一下!