4.1请求
4.1.1利用HTTP协议向服务器传参的几种途径
(1)请求行中的路径
(2)查询字符串
(3)请求体
(4)请求头
4.1.2使用正则提取URL中的参数
(1)位置参数
# url(r'^weather1/([a-z]+)/(\d{4})/$', views.weather),
def weather1(request, city, year):
"""读取正则中的组提取的参数"""
print('city=%s' % city)
print('year=%s' % year)
return HttpResponse('OK')
(2)关键字参数
# url(r'^weather2/(?P<city>[a-z]+)/(?P<year>\d{4})/$', views.weather2),
def weather2(request, year, city):
"""读取正则中的关键字提取的参数"""
print('city=%s' % city)
print('year=%s' % year)
return HttpResponse('OK')
4.1.3提取查询字符串参数
(1)需求:提取问号后面的查询字符串
/weather3/beijing/2018/?a=10&b=20&a=30
(2)属性
request.GET
返回QueryDict类型的对象
(3)QueryDict类型
可以存储一键一值和一键多值
提供get()方法:读取一键一值
提供getlist()方法:读取一键多值
(4)代码演练
# /weather3/beijing/2018/?a=10&b=20&a=30
def weather3(request, year, city):
"""提取查询字符串参数"""
print('city=%s' % city)
print('year=%s' % year)
a = request.GET.get('a')
b = request.GET.get('b')
a_list = request.GET.getlist('a')
print(a,b,a_list)
return HttpResponse('OK')
4.1.4提取请求体中的参数
(1)提取请求体中的表单数据
①属性
request.POST
返回QueryDict类型的对象
②代码演练
# url(r'^get_body_form/$', views.get_body_form),
def get_body_form(request):
"""演示获取请求体中的表单"""
a = request.POST.get('a')
b = request.POST.get('b')
alist = request.POST.getlist('a')
print(a)
print(b)
print(alist)
return HttpResponse('OK')
(2)提取请求体中的非表单数据
①属性
request.body
②代码演练
# url(r'^get_body_json/$', views.get_body_json),
# {"a": 1, "b": 2}
def get_body_json(request):
"""演示获取请求体中的⾮表单数据"""
print(request.META['CONTENT_TYPE'])
print(request.method, request.path)
json_str = request.body
json_str = json_str.decode()
req_data = json.loads(json_str)
print(req_data['a'])
print(req_data['b'])
return HttpResponse('OK')
4.1.5提取请求头中的信息
(1)提取方案
(2)代码实现
print(request.META['CONTENT_TYPE'])
4.1.6其它请求报文信息
print(request.method, request.path)
4.2响应
4.2.1HttpResponse
(1)概述
导入:from django.http import HttpResponse
视图在接收请求并处理后,必须返回HttpResponse对象或子对象
可以使用django.http.HttpResponse来构造响应对象。
HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
如: return HttpResponse('OK', content_type='text/html', status=200)
注意:响应体参数是必须传的
(2)自定义响应头
response = HttpResponse('OK', content_type='text/html', status=200)
response['Itcast'] = 'Python' # 自定义响应头Itcast, 值为Python
(3)HttpResponse子类
Django提供了一系列HttpResponse的子类,可以快速设置状态码
- HttpResponseRedirect 301
- HttpResponsePermanentRedirect 302
- HttpResponseNotModified 304
- HttpResponseBadRequest 400
- HttpResponseNotFound 404
- HttpResponseForbidden 403
- HttpResponseNotAllowed 405
- HttpResponseGone 410
- HttpResponseServerError 500
4.2.2JsonResponse
若要返回json数据,可以使用JsonResponse来构造响应对象,作用:
- 默认会设置状态码
- 默认会将数据类型设置为Content-Type:application/json
- 默认会将json字典转成json字符串,再将json字符串转成二进制响应给用户
如:
from django.http import JsonResponse
def response_json(request):
json_dict = {"name":"zxj","age":18}
return JsonResponse(json_dict)
4.2.3redirect重定向
#需求:重定向到users应用下的index视图
from django.shortcuts import redirect
def response_redirect(request):
#最原始的方式实现
return redirect(‘/users/index/’)
#使用反向解析实现重定向
return redirect(reverse('users:index'))
4.2.4render
用于响应模板数据