利用HTTP協議向服務器傳參的四種方式:前端
URL路徑參數python
a:未命令參數按定義順序傳遞django
url(r'^weather/(a-z]+)/(\d{4})/$', views.weather)json
def weather(request, city, year):服務器
print('city=%s' % city)post
print('year=%s' % year)測試
return HttpResponse("ok")url
未定義時,參數須要一一對應code
b:命名參數按名字傳遞orm
url(r'^weather/(?P<city>[a-z]+)/(?P<year>\d{4})$', views.weather)
def weather(request, year, city):
print('city=%s' % city)
print('year=%s' % year)
return HttpResponse("ok")
不須要一一對應,參數名稱對上便可
Django中的QueryDict對象
定義在django.http.QueryDict
HttpRequest對象的屬性GET,POST都是QueryDict類型的對象
與python字典不一樣,QueryDict類型的對象用來處理同一個鍵帶有多個值的狀況
方法get():根據鍵獲取值
若是一個鍵同時擁有多個值獲取最後一個值
若是鍵不存在則返回None值,能夠設置默認值進行後續處理
dict.get('鍵', 默認值) 可簡寫:dict['鍵']
方法getlist():根據鍵獲取值,值以列表返回,能夠設置默認值進行後續處理
dict.getlist('鍵',默認值)
查詢字符串Query String
獲取請求路徑中的查詢字符串參數(形如?k1=v1&k2=v2), 能夠經過request.GET屬性獲取,返回QueryDict對象
def get(request):
get_dict = request.GET
# ?a=10&b=python
a = get_dict.get('a')
b = get_dict.get('b')
print(type(a))
print(b)
return JsonResponse({'data':'json'})
def post1(request):
post_dict = request.POST
a = post_dict.get("a")
b = post_dict.get("b")
print(a)
print(b)
return JsonResponse({"data":"json"})
請求體
請求體數據格式不固定,能夠是JSON字符串,能夠是XML字符串,應區別對待.
能夠發送請求數據的請求方式有: POST, PUT, PATCH,DELETE.
Django默認開啓csrf防禦,會對上述請求方式進行csrf防禦驗證,在測試時能夠關閉csrf防禦機制,
表單類型Form Data
前端發送的表單類型的請求數據,能夠經過request.POST屬性獲取,返回QueryDict對象.
非表單類型的請求體數據,Django沒法自動解析,能夠經過request.boby屬性獲取最原始的請求數據,再解析,response.boby返回bytes類型
def boby(request):
# 獲取非表單數據,類型bytes
json_bytes = request.boby
# 轉字符串
json_str = json_bytes.decode()
# json.dumps() ===> 將字典轉字符串
# json.loads() == > 將字符串轉字典
json_dict = json.loads(json_str)
print(type(json_dict))
print(json_dict.get('a'))
print(json_dict('b'))
return HttpResponse('boby')
請求頭:
能夠經過request.META屬性獲取請求heades中的數據,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).