gpt4 book ai didi

django - Tastypie "always_return_data"选项更改响应状态代码

转载 作者:可可西里 更新时间:2023-11-01 17:27:57 25 4
gpt4 key购买 nike

我有一个 Tastypie API,我想在 POST 请求时获取创建资源的“id”,所以我找到的唯一解决方案是“always_return_data”,它返回整个对象。

from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie.authentication import SessionAuthentication

from myproject.core.models import MyModel


class MyResource(ModelResource):
...

class Meta:
queryset = MyModel.objects.all()
resource_name = 'mymodel'
allowed_methods = ['get', 'put', 'post']
authentication = SessionAuthentication()
authorization = Authorization()
always_return_data = True # Added later

这很好用。但是一开始我已经编写了测试并且有:

对于 POST:self.assertHttpCreated(self.api_client.post('self.detail_url', format='json', data=data))

对于 PUT:self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))

现在在我设置always_return_data = True 旧测试失败后,因为 POST 返回 200 而不是 201,PUT 重新调整 200 而不是 [202/204]除了将 assertHttpCreatedassertHttpAccepted 替换为 assertHttpOK 之外,还有其他解决方案吗?或者如果可能的话,是否可以只返回新的“id” - 在未设置 always_return_data = True 的情况下根据 POST 请求创建资源。欢迎任何建议。谢谢。

最佳答案

根据规范 ( http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6 ),状态码 200 似乎是合适的。

为了良好的实践,请始终使用 list_allowed_methodsdetail_allowed_methods而不是 allowed_methods。更改 allowed_methods = ['get', 'put', 'post'],并添加

list_allowed_methods = ['get', 'post']

detail_allowed_methods = ['get', 'put']

如果创建了新资源,则返回 HttpCreated(201 已创建)。如果 Meta.always_return_data = True,将会有序列化数据的填充体。

如果现有资源被修改并且 Meta.always_return_data = False(默认),返回 HttpNoContent(204 无内容)。如果修改了现有资源并且 Meta.always_return_data = True,则返回 HttpAccepted(200 OK)。

对于测试用例,连同assertHttpOK,您可以添加另一个测试用例来验证您在放置/发布时发送的响应数据对象和请求数据对象。

关于django - Tastypie "always_return_data"选项更改响应状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182855/

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