4

我在使用美味派并将数据发布到它时遇到问题。我只能检索 401 错误代码。

为了澄清起见,我能够成功地从 sweetpie api 中检索数据。

附件是代码片段,也许有人可以帮我解决这个问题。在开始之前,有一点背景知识:我正在使用自定义授权类。

    class CustomAuthorization(Authorization):
        def is_authorized(self, request, object=None):
            if request.user.username == 'custom_user':
                return True
            return False

这是实际的资源:

    class CustomObjectResource(ModelResource):
        class Meta:
            queryset = CustomObject.objects.all()
            authentication = ApiKeyAuthentication()
            authorization = CustomAuthorization()
            list_allowed_methods = ['get', 'post', ]
            detail_allowed_methods = ['get', 'post', 'put']
            include_resource_uri = False
            resource_name = 'customobject'
            always_return_data = True


        def obj_create(self, bundle, request=None, **kwargs):
            try:
                print "request"
            except:
                raise BadRequest('I couldnt save your information.')
            return True

我知道 obj_create 方法是伪造的,但它仍然应该被调用并做一些事情,或者这已经是问题了吗?

以下 curl 命令用于将数据发布到tastepie API。

    curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"body": "This will prbbly be my lst post.", "pub_date": "2011-05-22T00:46:38", "slug": "another-post", "title": "Another Post"}' http://local.com:8000/api/v1/customobject/?format=json&username=custom_user&api_key=123456789012345

api_key 是正确的,但在这种情况下是假的!

如前所述,get 方法有效,但 post 不起作用。

任何人都知道如何解决这个问题或有解决方法吗?

4

2 回答 2

1

我会尝试一些事情来调试这个问题。

1)尝试添加:allowed_methods = ['get', 'post', 'put']

2)在 custom_authorization 中添加打印语句以检查是否由于 request.user.username 不同而导致问题。

3)在APIKeyAuthentication的源中也做(2)。

这应该足以让您调试问题。完成后请记住删除打印语句!

祝你好运。

于 2012-07-26T02:09:37.513 回答
0

这可能是由于一个已知问题。目前在背景上,美味派将 POST 转换为 PUT,正如 Nikunj 指出的那样,因为在 list_allowed_methods 中你没有 PUT,所以 POST 也被阻止了……但不确定是否存在,因为在这种情况下你应该得到不允许的方法。我建议在“is_authorized”方法中进行调试并检查那里发生了什么。

于 2012-07-28T00:38:11.847 回答