对于我正在构建的应用程序,我想通过一个简单的装饰器提供行级权限。我可以这样做,因为条件只是 request.user 是否是模型对象的所有者。
以下似乎工作:
from functools import wraps
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
def is_owner_permission_required(model, pk_name='pk'):
def decorator(view_func):
def wrap(request, *args, **kwargs):
pk = kwargs.get(pk_name, None)
if pk is None:
raise RuntimeError('decorator requires pk argument to be set (got {} instead)'.format(kwargs))
is_owner_func = getattr(model, 'is_owner', None)
if is_owner_func is None:
raise RuntimeError('decorator requires model {} to provide is_owner function)'.format(model))
o=model.objects.get(pk=pk) #raises ObjectDoesNotExist
if o.is_owner(request.user):
return view_func(request, *args, **kwargs)
else:
raise PermissionDenied
return wraps(view_func)(wrap)
return decorator
风景:
@login_required
@is_owner_permission_required(Comment)
def edit_comment(request, pk):
...
网址:
url(r'^comment/(?P<pk>\d+)/edit/$', 'edit_comment'),
该模型:
class Comment(models.Model):
user = models.ForeignKey(User, ...
<...>
def is_owner(self, user):
return self.user == user
任何反馈或评论表示赞赏。
保罗·博尔曼斯