二、响应:
视图在接收请求并处理后,必须返回HttpResponse对象或子对象。
HttpRequest对象由Django创建,HttpResponse对象由开发人员创建。
1.HttpResponse:
from django.http import HttpResponse
使用方法:
HttpResponse(
content = "响应体",
content_type = "相应体数据类型",
status = 状态码
)
通过上式:
- content: 表示返回的内容;
- content_type: 指定返回数据的MIME类型;
- status: 返回HTTP响应的状态码;
代码演示:
# 定义一个视图函数
def demo_response(request):
# 定义一个json字符串
json_str = '{"name": "python"}'
# 返回一个HttpResponse响应对象
return HttpResponse(json_str, content_type = "application/json", status = 400 )
效果演示:
特别的使用方式:
如果需要在响应头添加自定义的键值对内容。
可以吧HttpResponse对象当做字典进行相应头键值对的设置
response = HttpResponse()
# 自定义响应头itcast,值为python
response["itcast"] = "python"
代码演示:
from django.http import HttpResponse
def demo_view(request):
return HttpResponse('itcast python', status=400 )
# 或者
response = HttpResponse("itcast python")
response.status = 400
response['itcast'] = 'python'
return response
效果演示:
2. HttpResponse子类:
Django提供了一系列HttpResponse的子类,可以快速的设置状态码
这个状态码可以从Django.http中导入:
from django.http import HttpResponseNotFound
子类名 | 状态码 | 说明 |
---|---|---|
HttpResponseRedirect | 301 | 重定向请求将会变成 GET 方式 |
HttpResponsePermanentRedirect | 302 | 请求的资源现在临时从不同的 URI 响应请求。 |
HttpResponseNotModified | 304 | 从缓存中读取 |
HttpResponseBadRequest | 400 | 请求参数有误 |
HttpResponseNotFound | 404 | 服务器端没有这个页面 |
HttpResponseForbidden | 403 | 服务器已经理解请求,但是拒绝执行它 |
HttpResponseNotAllowed | 405 | 请求行中指定的请求方法不能被用于请求相应的资源 |
HttpResponseGone | 410 | 被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址 |
HttpResponseServerError | 500 | 服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理 |
演示:
3.JsonResponse:
如果要返回json字符串,那么可以使用jsonResponse来快速的构建json字符串,进行返回;
JsonResponse能自动的把字典转成json字符串类型,并且还不用自己设置响应头中contentType字段
所以总结一下,JsonResponse能够帮助我们做到如下两点:
- 帮助我们讲数据转换为json字符串;
- 设置响应头content-Type为application/json
使用:
# 导入JsonResponse
from django.http import JsonResponse
def demo_view(response):
# 直接返回JsonResponse这个对象,并且里面可以直接传入参数
params = {
"city": "beijing",
"subject":"python"
}
return JsonResponse(params)
显示效果:
4.redirect重定向:
from django.shortcuts import redirect
def demo_view(request):
return redirect("/index.html")
演示效果:
说明:
- 建议redirect(重定向)和我们前面学习的recerse搭配使用.
- 尽量不要把路由写死,有利于我们更改开发代码.