利用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).