如何在tastypie中将详细信息对象传递给自定义授权?

时间:2012-07-10 22:34:58

标签: django tastypie

如何在tastypie授权期间访问请求中正在访问的详细端点对象?

我注意到docs中的一个被覆盖的方法有一个对象参数 - 我该如何设置它?

2 个答案:

答案 0 :(得分:3)

在分支烫发中,

https://github.com/toastdriven/django-tastypie/blob/perms/tastypie/authorization.py

类授权有一组方法,例如:

def read_detail(self, object_list, bundle):
    """
    Returns either ``True`` if the user is allowed to read the object in
    question or throw ``Unauthorized`` if they are not.
    Returns ``True`` by default.
    """
    return True

此处您可以尝试通过 bundle.obj

访问 obj

如果你不能使用perms分支,我建议你这样:

class MyBaseAuth(Authorization):
    def get_object(self, request):
        try:
            pk = resolve(request.path)[2]['pk']
        except IndexError, KeyError:
            object = None # or raise Exception('Wrong URI')
        else:
            try:
                object = self.resource_meta.object_class.objects.get(pk=pk)
            except self.resource_meta.DoesNotExist:
                object = None
        return object


class FooResourceAuthorization(MyBaseAuth):
    def is_authorized(self, request, object=None):
        if request.method in ('GET', 'POST'):
            return True
        elif request.method == 'DELETE':
            object = self.get_object(request)
            if object.profile = request.user.profile:
                return True
        return False

答案 1 :(得分:0)

Hackish,但是通过一种简单的方法从请求URL获取对象(受DjangoAuthorization内部代码的启发)。

def is_authorized(self, request, object=None):

    meta = self.resource_meta
    re_id = re.compile(meta.api_name + "/" + meta.resource_name + "/(\d+)/")
    id = re_id.findall(request.path)

    if id:
        object = meta.object_class.objects.get(id=id[0])

        # do whatever you want with the object
    else:
        # It's not an "object call"