美文网首页
django 返回 json 格式数据

django 返回 json 格式数据

作者: wangtieshan | 来源:发表于2017-10-06 22:57 被阅读0次

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)
image.png

相关文章

网友评论

      本文标题:django 返回 json 格式数据

      本文链接:https://www.haomeiwen.com/subject/tdtqjxtx.html