- Title(EN): Django REST Framework Learning Notes (6): the response module
- Author: dog2
基本信息
源码分析
响应类构造器:rest_framework.response.Response
1 2 3 4 5 6 7 8 9 10 11 12
| 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) """
|
用法示例
1 2 3 4 5
| from rest_framework import status
return Response(data={数据}, status=status.HTTP_200_OK, headers={设置的响应头})
|
二次封装Response类
可以自定义APIResponse以便于使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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=False, **kwargs): data = { 'status': data_status, 'msg': data_msg, } if results is not None: data['results'] = results data.update(kwargs)
super().__init__(data=data, status=http_status, headers=headers, exception=exception)
|