我正在使用tastype创建一个RESTful API。我遇到了基于django管理权限限制用户授权的问题。Per the docs,我正在尝试实现DjangoAuthorization()

class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = DjangoAuthorization()

目前,对fakeuser完全没有Django权限的用户myModel仍然可以从api获取数据。此用户被适当限制发布数据。
tl;dr如何扩展DjangoAuthorization()类,以限制在模型上没有Django权限的用户的GET

最佳答案

编写您自己的授权后端扩展自根据您的条件重写访问方法的DjangoAuthorization,下面是一个如何重写read_detail(GET)方法的示例:

from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import Unauthorized

class CustomDjangoAuthorization(DjangoAuthorization):

    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)

        # now we check here for specific permission
        if not bundle.request.user.has_perm('any_permission'):
            raise Unauthorized("You are not allowed to access that resource.")

        return result

现在在资源中使用CustomDjangoAuthorization类:
class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = CustomDjangoAuthorization()

10-08 04:37