2

我如何访问在美味派授权期间在请求中访问的详细端点对象?

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

4

2 回答 2

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
于 2012-07-11T10:02:07.170 回答
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"
于 2013-01-09T19:49:22.520 回答