【问题标题】:tastypie - where to restrict fields that may be updated by PATCH?美味派 - 在哪里限制可能由 PATCH 更新的字段?
【发布时间】:2012-12-04 13:44:18
【问题描述】:

我有一个有效的 GET/tastepie(只读)解决方案。

我已允许 PUT/PATCH 请求并成功修补记录。

但是,对于(已经)经过身份验证和授权的用户,我想将 PATCH 功能限制为仅在适当的模型资源上的某些字段。我仍然希望用户能够获取(查看)所有字段。

实现这种限制的最佳位置(方法?)在哪里?

文档: https://django-tastypie.readthedocs.org/en/latest/interacting.html?highlight=patch#partially-updating-an-existing-resource-patch

【问题讨论】:

    标签: python django patch tastypie


    【解决方案1】:

    有点晚了,但也许这会对某人有所帮助。

    我的解决方案是覆盖 update_in_place 并检查传递的数据。

    from tastypie.resources import ModelResource
    from tastypie.exceptions import BadRequest
    
    
    class MyResource(ModelResource):
        class Meta:
            ...
            allowed_update_fields = ['field1', 'field2']
    
        def update_in_place(self, request, original_bundle, new_data):
            if set(new_data.keys()) - set(self._meta.allowed_update_fields):
                raise BadRequest(
                    'Only update on %s allowed' % ', '.join(
                        self._meta.allowed_update_fields
                    )
                )
    
            return super(MyResource, self).update_in_place(
                request, original_bundle, new_data
            )
    

    【讨论】:

    • BadRequest 来自tastypie.exceptions。
    • “有点晚了,但也许这会对某人有所帮助。” ..它只是为我节省了几个小时逐行寻找此功能以覆盖的时间。 :)
    【解决方案2】:

    由于您似乎已经为用户授权,您应该能够通过添加到您的 ModelResource 中的 Meta 类来实现这一点。例如,使用 DjangoAuthorization (from tastypie docs):

    from tastypie.authentication import BasicAuthentication
    from tastypie.authorization import DjangoAuthorization
    ...
    
    class SomeResource(ModelResource):
      ...
      class Meta:
        ...
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
    

    此示例将为您提供django.contrib.auth.models.Permission 中定义的操作的用户授权。

    我还收到了来自tastepie Google Group 的this。它使用dehydrate method。以下是 Google Groups 链接中提供的示例:

    def dehydrate(self, bundle): 
     bundle = super(self, MyResource).dehydrate(bundle) 
    
     # exclude the restricted field for users w/o the permission foo 
     if not bundle.request.user.has_perm('app.foo'): 
         del bundle.data['restricted'] 
    
     return bundle 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-17
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2012-10-30
      • 2014-01-23
      相关资源
      最近更新 更多