Django框架——HttpResponse对象


1.HttpResponse

可通过HttpResponse构造响应对象:

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:

response = HttpResponse()
response['itcast'] = 'Python'  # 自定义响应头Itcast, 值为Python

Django提供了一系列HttpResponse的子类,可以快速设置状态码:

HttpResponseRedirect 301
HttpResponsePermanentRedirect 302
HttpResponseNotModified 304
HttpResponseBadRequest 400
HttpResponseNotFound 404
HttpResponseForbidden 403
HttpResponseNotAllowed 405
HttpResponseGone 410
HttpResponseServerError 500

2.JsonResponse

JsonResponse来构造响应对象的作用:
(1)帮助我们将数据转换为json字符串
(2)设置响应头Content-Type为application/json

用法:
return JsonResponse(dict,safe) (safe默认为True,保证可以将对象转为json,如果为非字典对象,则报错,可设置为False传递非字典对象)
例:

def response(request):
	 return JsonResponse({'city': 'beijing', 'subject': 'python'})

3.redirect重定向

return redirect(路径)

4.reverse反解析

reverse可根据路由名称返回路由路径。
用法:

reverse(路由名称)

如果未指明命名空间,路由名称:

namespace:reverse(name)

如果指明命名空间,路由名称:

namespace:reverse(namespace:name)

猜你喜欢

转载自blog.csdn.net/zsh142537/article/details/83616600