gpt4 book ai didi

django - Tastypie 以 Json 格式响应每个请求

转载 作者:行者123 更新时间:2023-12-01 06:32:03 24 4
gpt4 key购买 nike

我正在为我的项目开发 Api,我使用的是 Tastypie 9.9.0。我想要 Json 格式的响应以用于 PUT、POST 和 DELETE 操作。

现有的响应如 STATUS 201 CREATED、STATUS 204 NO CONTENT、STATUS 410 GONE 很好。

它必须以自定义格式响应。
例如

1.  {
"resource_name": "user",
"action":"password_reset",
"status": "success"
}

2. {
"resource_name": "todo",
"action":"insert",
"status":"sucess",
}
3. {
"resource_name": "todo",
"action":"delete",
"status":"sucess",
}

这是我正在处理的代码。我不知道如何添加自定义响应消息
  class ToDoResource(ModelResource):
user = fields.ToOneField(UserResource, 'user')

class Meta:
queryset = ToDo.objects.all()
fields=['alert_time','description','status','user']
resource_name = 'todo'
filtering = {
'user': ALL_WITH_RELATIONS,
'alert_time': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'],
}
serializer = Serializer()
authentication= MyApiKeyAuthentication()
authorization=Authorization()
always_return_data = True
allowed_methods = ['post','get','put','delete']


def obj_create(self, bundle,request=None, **kwargs):
if not request.user.is_superuser:
try:
bundle.data.pop('user')
except:
pass
return super(ToDoResource, self).obj_create(bundle, request, user=request.user)

def create_response(self, request, data):
"""
Extracts the common "which-format/serialize/return-response" cycle.

Mostly a useful shortcut/hook.
"""
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))

def apply_authorization_limits(self, request, object_list):
return object_list.filter(user=request.user)

最佳答案

您可以在 get_list(request, **kwargs) 和/或 get_object(request, **kwargs) 中添加/修改自定义数据

例如,

import json
from django.http import HttpResponse

class ToDoResource(ModelResource):
# ... the rest of code
def get_list(self, request, **kwargs):
resp = super(ToDoResource, self).get_list(request, **kwargs)
data = json.loads(resp.content)

# ... the rest of code

data['meta']['resource_name'] = self._meta.resource_name
data['meta']['action'] = request.method
data['meta']['status'] = ANY_STATUS

# ... the rest of code

data = json.dumps(data)

return HttpResponse(data, mimetype='application/json', status=ANY_STATUS)

关于django - Tastypie 以 Json 格式响应每个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19218355/

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