Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Tastypie中,覆盖资源的正确方法是什么?\u被授权()实现行级权限吗_Python_Django_Tastypie - Fatal编程技术网

Python 在Tastypie中,覆盖资源的正确方法是什么?\u被授权()实现行级权限吗

Python 在Tastypie中,覆盖资源的正确方法是什么?\u被授权()实现行级权限吗,python,django,tastypie,Python,Django,Tastypie,我已向Tastype资源添加了行级授权,如下所示: from tastypie.exceptions import ImmediateHttpResponse from tastypie.http import HttpUnauthorized class MyResource(ModelResources): ... def is_authorized(self, request, object=None): super(MyResource, self).i

我已向Tastype资源添加了行级授权,如下所示:

from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpUnauthorized

class MyResource(ModelResources):
    ...
    def is_authorized(self, request, object=None):
        super(MyResource, self).is_authorized(request, object)
        if object and (object.user != request.user):
            raise ImmediateHttpResponse(response=HttpUnauthorized())
为简洁起见,我省略了通常的导入,只指定了与问题相关的导入


我的问题是,有没有更干净的方法来覆盖
已授权的
,而不必立即导入
ttpreponse
HttpUnauthorized
?在我看来,这些都是实现细节,我应该能够简单地返回
True
False

,尽管您的代码非常好,但是如果您不想导入响应类,那么一种更简洁的方法是编写一个授权类并在资源类中使用它

from tastypie.authorization import Authorization
class RowLevelAuthorization(Authorization):
    def is_authorized(self, request, object=None):
        if object and (object.user != request.user):
            return False
        else:
            return True

class MyResource(ModelResources):
    class Meta:
        authorization = RowLevelAuthorization()

tastypie 0.9.12的文档就是一个很好的例子

以下是“阅读”部分——其余部分请参阅文档:

class UserObjectsOnlyAuthorization(Authorization):

    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        return object_list.filter(user=bundle.request.user)

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return bundle.obj.user == bundle.request.user

    # DON'T FORGET TO IMPLEMENT METHODS FOR CREATE/UPDATE/DELETE as shown in the docs.

您会注意到
UserObjectsOnlyAuthorization.read_detail()
返回True/False。
read\u list
方法将返回一个空列表,根据文档,这是可以接受的,但是如果您愿意,您也可以引发
未经授权的
异常。

从长远来看,您最好将django guardian与以下授权类集成到您的应用程序中:


我在Tastypie文档中找不到任何关于授权的引用。is_authorized()。你能提供一个验证这种方法的链接吗?这里是提到这种方法的链接。我不确定
是否经过授权
方法在最新版本中已被删除/隐藏。