我在做一个类生成器。我希望能够创建BasePermission
的许多子级,这些子级可以使用required_scopes
属性进行自定义。这就是我目前所拥有的
from rest_framework.permissions import BasePermission
class ScopedPermissionMeta(type(BasePermission)):
def __init__(self, name, bases, attrs):
try:
required_scopes = attrs['required_scopes']
except KeyError:
raise TypeError(f'{name} must include required_scopes attribute.')
required_scopes_list = ' '.join(required_scopes)
attrs['message'] = f'Resource requires scope={required_scopes_list}'
def has_permission(self, request, _view):
"""Check required scopes against requested scopes."""
try:
requested_scopes = request.auth.claims['scope']
except (AttributeError, KeyError):
return False
return all(scope in requested_scopes for scope in required_scopes)
attrs['has_permission'] = has_permission
class ReadJwtPermission(BasePermission, metaclass=ScopedPermissionMeta):
required_scopes = ['read:jwt']
但是,我不喜欢ReadJwtPermisson
类(以及更多的子类)必须指定元类的方式。理想情况下,我想把那个细节抽象出来。我希望能够做到以下几点:
class ScopedPermission(BasePermission, metaclass=ScopedPermissionMeta):
pass
class ReadJwtPermission(ScopedPermission):
required_scopes = ['read:jwt']
但是在这种情况下,元类see是ScopedPermission
和norequired_scopes
。有没有办法让元类看穿这种继承关系
在创建
ScopedPermission
类时,没有ReadJwtPermission
类。解释器无法预测将来某个类将成为具有required_scopes
属性的子类ScopedPermission
。但是你可以做一些不同的事情子类继承父类的元类。如果父类使用该元类,则每个子类都必须具有所需的属性。我还使用
__new__
在类创建之前检查该属性。以下是一个例子:输出:
但现在:
这会引起错误
相关问题 更多 >
编程相关推荐