REST framework 響應模塊

from rest_framework.response import Response

源碼

class Response(SimpleTemplateResponse)
    def __init__(self, data=None, status=None,
                 template_name=None, headers=None,
                 exception=False, content_type=None):
     """
        :param data: 響應數據
        :param status: http響應狀態碼
        :param template_name: drf也可以渲染頁面,渲染的頁面模板地址(不用瞭解)
        :param headers: 響應頭
        :param exception: 是否異常了
        :param content_type: 響應的數據格式(一般不用處理,響應頭中帶了,且默認是json)
    """
    pass

使用:常規實例化響應對象

# status就是解釋一堆 數字 網絡狀態碼的模塊
from rest_framework import status就是解釋一堆 數字 網絡狀態碼的模塊
# 一般情況下只需要返回數據,status和headers都有默認值
return Response(data={數據}, status=status.HTTP_200_OK, headers={設置的響應頭})

 自定義響應模塊

responses.py

from rest_framework.response import Response

class APIResponse(Response):
    def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=None, **kwargs):
        # data的初始狀態: 狀態碼與狀態信息
        data = {
            'status': data_status,
            'msg':data_msg
        }
        # data的響應數據體: results (其可能是False,0等數據, 這些數據某些情況下也會作爲合法數據返回)
        if results is not None:
            data['results'] = results
        # data響應的其他內容:
        # if kwargs is not None:
        #     for k, v in kwargs.items():
        #         setattr(data, k, v)
        data.update(kwargs)
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)

 

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