用戶發送請求時攜帶的引數后端需要使用,而不同的發送引數的方式對應了不同的提取引數的方式*
利用HTTP協議向服務器傳參有幾種途徑?
1.查詢字串資料(query string):
形如:?key1=value1&key2=value2
比如:http://127.0.0.1:8000/?name =lx&age=0中的?name =lx
1)獲取請求路徑中的查詢字串引數,形如:?k1=v1&k2=v2
2)可以通過request.GET屬性獲取,并回傳QueryDict型別的物件
class TestQuery(View):
def get(self, request):
# 獲取查詢字串引數name、age
name = request.GET.get('name', 'lx')
age = request.GET.get('age', '0')
return HttpResponse('查詢字串引數:%s %s' % (name, age))

重要提示:
提取查詢字串引數不區分請求方式,即使客戶端進行POST方式的請求,依然可以通過request.GET獲取請求中的查詢字串引數,
QueryDict補充:
1)QueryDict是由Django自己封裝的一個資料型別,繼承自python的字典Dict,它被定義在django.http.QueryDict中專門用來存盤請求中提取的查詢字串引數和請求體引數.即,HttpRequest物件中的屬性GET、POST都是QueryDict型別的資料
2. 提取請求體資料
1)可以發送請求體資料的請求方式有:POST、PUT、PATCH、DELETE
2)請求體資料格式不固定,常見的有:表單型別資料和JSON字串型別,我們應區別對待
2.1 表單型別請求體資料(Form Data)
前端發送的表單型別的請求體資料,可以通過request.POST屬性獲取,并回傳QueryDict物件,
class TestQuery(View):
def post(self, request):
# 獲取表單型別請求體引數中的username、password
username = request.POST.get('username')
password = request.POST.get('password')
return HttpResponse('表單型別請求體引數:%s %s' % (username, password))
重要提示:
request.POST只能用來獲取POST表單發送的請求體資料

2.2 非表單型別請求體資料(Non-Form Data):JSON
1)非表單型別的請求體資料,Django無法自動決議,可以通過request.body屬性獲取最原始的請求體資料
2)request.body獲取的是bytes型別的請求體原始資料
class TestQuery(View):
def post(self, request):
# 獲取請求體中原始的JSON資料
json_str = request.body
# 使用json模塊將原始的JSON資料轉字典
json_dict = json.loads(json_str)
# 請求體引數中的username、password
username = json_dict.get('username')
password = json_dict.get('password')
return HttpResponse('表單型別請求體引數:%s %s' % (username, password))
結果展示:

3. URL路徑引數:提取URL路徑中的特定部分資料
1)在定義路由時,可以從URL中獲取特定部分的路徑引數
2)Django的路由系統會將提取的路徑引數傳遞到視圖的內部
3)path()和re_path()都可以提取路徑引數
需求1:http://127.0.0.1:8000/pratice/register/18/
提取路徑中的數字18
需求2:http://127.0.0.1:8000/pratice/register/18500000000/
提取路徑中的手機號18500000000
3.1 path()提取路徑引數
測驗path()提取普通路徑引數:http://127.0.0.1:8000/pratice/register/18/
path(‘pratice/register/int:age/’, views.URLParam1View.as_view()),
class TestQuery(View):
def get(self, request, age):
#提取路徑引數是在路由中完成的,因為路徑是在路由系統中處理的
print('提取的路徑傳參:',age)
return HttpResponse('path()提取普通路徑引數:%s' % age)

- 路由中提取路徑引數時,使用的關鍵字,必須跟視圖中引數名一致
思考:
實作需求1時提取age數字的int:age是什么?
路由轉換器
Django默認封裝了一些正則運算式,用于在path()中要提取路徑引數時使用
默認的路由轉換器:
位置在django.urls.converters.py
DEFAULT_CONVERTERS = {
'int': IntConverter(), # 匹配正整數,包含0
'path': PathConverter(), # 匹配任何非空字串,包含了路徑分隔符
'slug': SlugConverter(), # 匹配字母、數字以及橫杠、下劃線組成的字串
'str': StringConverter(), # 匹配除了路徑分隔符(/)之外的非空字串,這是默認的形式
'uuid': UUIDConverter(), # 匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00
}
原始碼決議:

實作需求2
http://127.0.0.1:8000/pratice/register/18500000000/
提取路徑中的手機號18500000000
問題:
1)默認的路由轉換器中,沒有專門用來匹配手機號的路由轉換器
2)所以在使用path()實作需求2時,就無法直接使用默認的路由轉換器
解決方案:
如果默認的路由轉換器無法滿足需求時,我們就需要自定義路由轉換器
在任意可以被匯入的python檔案中,都可以自定義路由轉換器
from django.urls import path, register_converter
from . import views
class MobileConverter:
"""自定義路由轉換器:匹配手機號"""
# 匹配手機號碼的正則
regex = '1[3-9]\d{9}'
def to_python(self, value):
# 將匹配結果傳遞到視圖內部時使用
return int(value)
def to_url(self, value):
# 將匹配結果用于反向決議傳值時使用
return str(value)
# 注冊自定義路由轉換器
# register_converter(自定義路由轉換器, '別名')
register_converter(MobileConverter, 'mobile')
urlpatterns = [
# path('pratice/register/<‘路由轉換器’:<變數>, views.TestQuery.as_view()),
# path('pratice/register/<int:age>', views.TestQuery.as_view()),
path('pratice/register/<mobile:phone_num>', views.TestQuery.as_view()),
]
class TestQuery(View):
def get(self, request,phone_num):
#提取路徑引數是在路由中完成的,因為路徑是在路由系統中處理的
print('提取的路徑傳參:',phone_num)
return HttpResponse('path()提取普通路徑引數:%s' % phone_num)
效果展示

3.2 re_path()提取路徑引數
re_path(r'^pratice/register/(?P<phone_num>1[3-9]\d{9})/$', views.TestQuery.as_view()),
class TestQuery(View):
def get(self, request,phone_num):
#提取路徑引數是在路由中完成的,因為路徑是在路由系統中處理的
print('提取的路徑傳參:',phone_num)
return HttpResponse('path()提取普通路徑引數:%s' % phone_num)
3.3 path()和re_path()如何選擇?
1)path()語法相對簡潔一些,如果沒有路徑引數要提取或者要提取的路徑引數可以使用默認的路由轉換器實作時,就選擇path(),
2)re_path()語法相對復雜一些,但是,如果希望在匹配路由時,由自己撰寫所有的正則式,就選擇re_path(),
需要注意的是,在使用re_path()時,網路地址正則運算式一定要寫完整,要有嚴格的開頭和結尾
4. 請求頭
可以通過request.META屬性獲取請求頭headers中的資料,request.META為字典型別,
常見的請求頭如:
CONTENT_LENGTH – The length of the request body (as a string).
CONTENT_TYPE – The MIME type of the request body.
HTTP_ACCEPT – Acceptable content types for the response.
HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
HTTP_HOST – The HTTP Host header sent by the client.
HTTP_REFERER – The referring page, if any.
HTTP_USER_AGENT – The client’s user-agent string.
QUERY_STRING – The query string, as a single (unparsed) string.
REMOTE_ADDR – The IP address of the client.
REMOTE_HOST – The hostname of the client.
REMOTE_USER – The user authenticated by the Web server, if any.
REQUEST_METHOD – A string such as "GET" or "POST".
SERVER_NAME – The hostname of the server.
SERVER_PORT – The port of the server (as a string).
class HeadersParamView(View):
"""提取請求頭引數"""
def get(self, request):
# 獲取請求頭中檔案的型別
ret = request.META.get('CONTENT_TYPE')
return http.HttpResponse('go')
5. 其他常用HttpRequest物件屬性
method:一個字串,表示請求使用的HTTP方法,常用值包括:'GET'、'POST',
FILES:一個類似于字典的物件,包含所有的上傳檔案,
COOKIES:一個字串,包含了瀏覽器自動發送的cookie快取資料,
user:請求中認證出來的用戶物件,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/294219.html
標籤:python
