我想控制每个api url的权限,包括方法(post,get,put,delete),怎么办?
我尝试了以下代码:
from multiselectfield import MultiSelectField
METHOD_CHOICES = (
('get','get'),
('post','post'),
('put','put'),
('delete','delete')
)
class ApiPermessions(models.Model):
name = models.CharField(max_length=20, unique=True, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
apiuri = models.CharField(max_length=20, verbose_name=u'授权api')
code = models.CharField(max_length=4, default=0000, null=True, blank=True, verbose_name=u'权限代码')
choices = MultiSelectField(choices=METHOD_CHOICES)
答案 0 :(得分:0)
您可以在django-rest-framework应用程序中创建自定义权限类。请参阅their docs here。
为了给你一个大纲,这看起来像是一个定义这些权限的类:
from rest_framework import permissions, exceptions
class CustomUserPermissions(permissions.BasePermission):
def has_permission(self, request, view):
request_method = request.method
request_user = getattr(request, 'user')
if request_user:
# Returns true if the request method is
# in the permissions set of the user object
return request_method in \
user.api_permissions_set.all().values_list('choices', flat=True)
您可以将其定义为rest框架配置中的权限类,通过它可以自动适用于所有视图。
'DEFAULT_PERMISSION_CLASSES': (
'CustomUserPermissions',
)