1.返回的格式需要是json数据格式的时候,将content 格式为json对象即可:
from django.http import HttpResponse
import json
def test(request):
resp = {
'code': '200',
'message': 'success',
'data': {
'num': '1234',
},
}
response = HttpResponse(content=json.dumps(resp), content_type='application/json;charset = utf-8',
status='200',
reason='success',
charset='utf-8')
return response
2. 封装 HttpResponse
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)