【问题标题】:How to access current user in tastypie patch request如何在美味派补丁请求中访问当前用户
【发布时间】:2013-05-23 11:55:45
【问题描述】:

我正在尝试使用 PATCH 请求发布多个对象,但出现以下错误: "error_message": "'HttpRequest' object has no attribute 'user'"

我的资源模型如下:

class TrackerResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        queryset = Tracker.objects.all()
        resource_name = 'tracker'
        allowed_methods = ['post','patch','put']
        detail_allowed_methods = ['post','patch','put']
        authentication = ApiKeyAuthentication()
        authorization = Authorization() 
        always_return_data =  True
        fields = ['data','tracker_date','badges','module','completed']


    def hydrate(self, bundle, request=None):
        bundle.obj.user = bundle.request.user
        bundle.obj.ip = bundle.request.META.get('REMOTE_ADDR','0.0.0.0')
        bundle.obj.agent = bundle.request.META.get('HTTP_USER_AGENT','unknown')
        return bundle 

我提出的 curl 请求是(使用正确的 api_key):

curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X PATCH --data '{"objects":[{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":1},{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":0}]}' "http://localhost/python/modules/api/v1/tracker/?username=alex&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx"

如果我只发布一个对象,它工作正常:

curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data '{"digest":"e5b24a362259b1408161829737f8ef3c","data":"{}","completed":0}' "http://localhost/python/modules/api/v1/tracker/?username=alex&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx"

那么,当我发出 PATCH 请求时,访问当前用户对象的正确方法是什么?还是我需要做一些事情来让 PATCH 请求将当前请求发送到每个 hydrate 方法?

非常感谢任何帮助。

【问题讨论】:

    标签: tastypie


    【解决方案1】:

    好吧,我现在已经开始工作了,需要在我的 TrackerResource 中添加一个 patch_list 方法:

    def patch_list(self,request,**kwargs):
        request = convert_post_to_patch(request)
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        for data in deserialized["objects"]:
            data = self.alter_deserialized_detail_data(request, data)
            bundle = self.build_bundle(data=dict_strip_unicode_keys(data))
            bundle.request.user = request.user
            self.obj_create(bundle, request=request)
        return http.HttpAccepted()
    

    不确定这是否真的是最好的处理方法,但对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-10
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2011-05-17
      相关资源
      最近更新 更多