3

我需要在 hydrate 方法中获取授权用户对象,如下所示:

class SalepointResource(ModelResource):
  def hydrate(self, bundle):
    user = bundle.request.user

但是这里的请求是空的HttpRequest对象,并且没有用户方法,虽然用户是授权的。有没有办法获取用户对象?

4

3 回答 3

0

您是否在美味派中正确设置了身份验证/授权?

于 2012-03-20T14:20:53.523 回答
0

使用 TastyPie 0.9.15,我发现这很有效:

def hydrate_user(self, bundle):
    bundle.obj.user = bundle.request.user
    return bundle

无需子类化ModelResource。这userForeignKey模型和资源的一个。我将其发布为答案,因为尽管它看起来很简单,但我花了很长时间才弄清楚。

于 2013-07-29T01:20:50.443 回答
0

不确定这是否是最好的方法,但我通过子类化ModelResource该类并覆盖它的一些方法来解决这个问题。在对象ModelResourcerequest(包含user)是方法的参数,obj_update但它没有传递给full_hydrate方法,而方法又调用hydrate. 您必须对这些方法中的每一个进行一些小的更改才能将request对象一直传递到链中。

方法修改是微不足道的。详细地:

from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from tastypie.resources import ModelResource
from tastypie.exceptions import NotFound, BadRequest, InvalidFilterError, HydrationError, InvalidSortError, ImmediateHttpResponse

class MyModelResource(ModelResource):
    def obj_create(self, bundle, request=None, **kwargs):
        ...
        bundle = self.full_hydrate(bundle, request)
        ...

    def obj_update(self, bundle, request=None, **kwargs):
        ...
        bundle = self.full_hydrate(bundle, request)
        ...

    def full_hydrate(self, bundle, request=None):
        ...
        bundle = self.hydrate(bundle, request)
        ...

    def hydrate(self, bundle, request=None):
        ...
        return bundle

然后使您的资源成为这个新类的子类并覆盖新版本hydrate

class MyModelResource(MyModelResource):
    class Meta:
        queryset = MyModel.objects.all()

    def hydrate(self, bundle, request):
        bundle.obj.updated_by_id = request.user.id
        return bundle

我还没有彻底测试过这个,但它似乎到目前为止工作。希望能帮助到你。

于 2012-09-19T21:36:30.263 回答