首页 文章

Tastypie“always_return_data”选项更改了响应状态代码

提问于
浏览
1

我有一个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 旧测试失败后,coz POST返回200而不是201并且PUT重新调整200而不是[202/204]除了用 assertHttpCreated 替换 assertHttpCreatedassertHttpAccepted 之外是否有解决方案或者如果可能,是否可能只需在POST请求中返回新创建的资源"id"而不设置 always_return_data = True . 任何建议都是受欢迎的 . 谢谢 .

1 回答

  • 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 No Content) . 如果现有资源已修改且 Meta.always_return_data = True ,则返回 HttpAccepted (200 OK) .

    对于测试用例,与 assertHttpOK 一起,您可以添加另一个测试用例来验证响应数据对象并请求在发送/发布时发送的数据对象 .

相关问题