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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章