【问题标题】:Tastypie "always_return_data" option changed response Status codes美味的“always_return_data”选项更改了响应状态代码
【发布时间】:2017-04-03 10:58:46
【问题描述】:

我有一个 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] 除了用assertHttpOK 替换assertHttpCreatedassertHttpAccepted 之外,还有其他解决方案吗?或者如果可能的话,是否可以在不设置always_return_data = True 的情况下仅在POST 请求中返回新创建资源的“id”。欢迎任何建议。谢谢。

【问题讨论】:

    标签: django rest http tastypie


    【解决方案1】:

    根据规范 (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 Created)。如果Meta.always_return_data = True,将有一个填充的序列化数据体。

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

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

    【讨论】:

    • 谢谢你的回答,很有用。我知道 PUT 或 POST 上的 200 OK 是合适的,但如果可能的话,我试图更准确。
    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多