我有一个 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]
除了将 assertHttpCreated
和 assertHttpAccepted
替换为 assertHttpOK
之外,还有其他解决方案吗?或者如果可能的话,是否可以只返回新的“id” - 在未设置 always_return_data = True
的情况下根据 POST 请求创建资源。欢迎任何建议。谢谢。
最佳答案
根据规范 ( http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6 ),状态码 200
似乎是合适的。
为了良好的实践,请始终使用 list_allowed_methods
和 detail_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/