问题
How can I access the detail endpoint object being accessed in the request during a tastypie authorization?
I noticed that one of the overridden methods in the docs has an object parameter -- how can I set this?
回答1:
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
回答2:
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"
来源:https://stackoverflow.com/questions/11423030/how-can-i-pass-a-detail-object-to-custom-authorization-in-tastypie