gpt4 book ai didi

Django REST framework : how to wrap the response with extra fields . ... 并在数据字段中提供当前响应

转载 作者:行者123 更新时间:2023-12-04 11:30:56 24 4
gpt4 key购买 nike

所以,我有以下几点:

class ObjectViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet
):
"""
REST API endpoints for Objects.
"""
serializer_class = ObjectSerializer
queryset = Object.objects.all()

例如,这将返回一个列表 GET要求:
[
{
"uuid": "787573a2-b4f1-40df-9e3a-8555fd873461",
},
{
"uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665",
}
]

但是,我怎样才能稍微改变这种混合的响应,使其类似于以下内容:
{
success: true,
message: 'Some Extra Useful Message',
data: [
{
"uuid": "787573a2-b4f1-40df-9e3a-8555fd873461",
},
{
"uuid": "2ab56449-1be1-47d7-aceb-a9eaefa49665",
}
]
}

这是可能的,还是我应该编写自己的自定义端点 Response()并且不使用 DRF mixins能力?

所以,基本上,切换自定义:
Response(data, status=None, template_name=None, headers=None, content_type=None)

到:

response = {
'success': true,
'message': 'Some Extra Useful Message',
'data': serializer.data
}

Response(response, status=None, template_name=None, headers=None, content_type=None)

最佳答案

您可以使用 Middelwares 处理此响应格式。 .如果基于状态代码你有一个固定的响应格式,那么编写一个中间件。

class ResponseFormatMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)
try:
if (not getattr(response, 'error', False)) and (isinstance(response.data, dict) or isinstance(response.data, list)):
response.data = {'success': True, 'message':'some message','data': response.data}
except AttributeError:
pass
return response

中间件写在 CustomMiddleware模块为 middleware.py , 然后加

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'CustomMiddleware.middleware.ResponseFormatMiddleware', # Added this line
]

settings.py文件。

关于Django REST framework : how to wrap the response with extra fields . ... 并在数据字段中提供当前响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60210652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com