django 返回 json 格式数据

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)
django 返回 json 格式数据_第1张图片
image.png

你可能感兴趣的:(django 返回 json 格式数据)