1.提取URL的特定部分,如/weather/shanghai/2019,可以在服务器端的路由中用正则表达式截取;
在reqresp/urls.py中代码如下:
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^weather/[a-z]+/\d{4}/$', views.weather) #未命名参数的方法 (位置)
url(r'^weather/(?P<city>[a-z]+)/(?P<year>\d{4})/$', views.weather) #命名参数的方法 (键)
#命名参数的方法适用于多个参数传参
]
#在reqresp/views.py中代码如下:
from django.http import HttpRseponse
def weather(request, year, city):
print(city)
print(year)
return HttpResponse('ok')
2.查询字符串(query string),形如
key1=value1&key2=value2;
"""127.0.0.1:8000/weather/shanghai/2019/?a=1&b=2&c=3"""
def weather(request, year, city):
# 查询字符串参数
a = request.GET.get('a')
b = request.GET.get('b')
alist = request.GET.getlist('a')
print(a)
print(b)
print(alist)
return HttpResponse('ok')
3.请求体(body)中发送的数据,比如表单数据、json、xml;
"""127.0.0.1:8000/weather/shanghai/2019/?a=1&b=2&c=3&d=4"""
def weather(request, year, city):
# 表单数据
c = request.POST.get('c')
d = request.POST.get('d')
clist = request.POST.getlist('c')
print(c)
print(d)
print(clist)
return HttpResponse('ok')
#注意重要点:
"""只要请求体的数据是表单类型,无论是哪种请求方式(POST、PUT、PATCH、DELETE),都是使用request.POST来获取请求体的表单数据。"""
# json
json_bytes = request.body
json_str = json_bytes.decode()
#json.loads() # python3.6或以上版本支持 str, bytes;
req_json = json.loads(json_str) #把 json_str 转化成python字典
c = req_json.get('c')
d = req_json.get('d')
print(c)
print(d)
return HttpResponse('ok')
#注意点:
"""json是非表单类型的请求体数据,Django无法自动解析,可以通过request.body属性获取最原始的请求体数据,自己按照请求体格式(JSON、XML等)进行解析。request.body返回bytes类型。"""
4.在http报文的头(header)中。
可以通过request.META属性获取请求头headers中的数据,request.META为字典类型。
def get_headers(request):
print(request.META['CONTENT_TYPE'])
return HttpResponse('OK')
以上代码用到了 CONTENT_TYPE(The MIME type of the request body.)