How can I pass a detail object to custom authorization in tastypie?

。_饼干妹妹 提交于 2019-12-04 16:12:34

In branch perms,

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

Class Authorization has a set of methods for example:

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

Here You can try to access the obj through bundle.obj

If You can't use the perms branch, I suggest you this way:

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

Hackish, but with a simple way of getting to the object from the request URL (inspired by the code inside 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"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!