HttpResponse和JsonResponse
Django处事器接收到客户端发送过来的请求后,,会将提交上来的这些数据封装成一个HttpRequest东西传给视图函数。那么视图函数在措置惩罚惩罚完相关的逻辑后,也需要返回一个响应给浏览器。而这个响应,我们必需返回HttpResponseBase或者他的子类的东西。而HttpResponse则是HttpResponseBase用得最多的子类。
常用属性及其含义:
content:返回的内容。
status_code:返回的HTTP响应状态码。
def index(request): response.content=‘wanrou‘ #相当于response = HttpResponse(‘wanrou‘) response.status_code=400 #设置错的HTTP响应状态码 在network中检察 return response
content_type:返回数据MIME媒体类型(简称MIME类型)默认是text/html。常见得content-type类型如下:
text/html(默认的,html文件)
text/plain(纯文本)
text/css(css文件)
text/javascript(js文件)
multipart/form-data(文件提交)
application/json(json传输)
application/xml(xml文件)
设置请求头:response[‘X-Access-Token‘] = ‘xxx‘
常用要领:
set_cookie:用来设置cookie信息.
delete_cookie:用来删除cookie信息
write:HttpResponse是一个类似于文件的东西,可以用来写入数据到数据中
def index(request): response = HttpResponse(‘hello‘) response.write(‘everyone‘) return response
JsonResponse把东西dump成json字符转,然后返回将json字符串封装成Response东西返回给浏览器。
from django.http import JsonResponse
def index(request):
a=JsonResponse({"username":"wanrou","age":18})
print(a.get(‘content-type‘))
#此时功效为application/json
return a
他的东西只能是字典,如果要给给字典数据进行jump,需要增加safe=False参数
from django.http import JsonResponse def index(request): persons = [‘张三‘,‘李四‘,‘王五‘] return HttpResponse(persons,safe=False) #如果不增加safe=False网页会报错
HttpResponse和JsonResponse
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30481.html