元类如何访问在子类上定义的属性?

2024-10-02 18:14:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个类生成器。我希望能够创建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。有没有办法让元类看穿这种继承关系


Tags: nameselfdefrequiredattrsclasshaspermission
1条回答
网友
1楼 · 发布于 2024-10-02 18:14:38

but in this situation the metaclass see's ScopedPermission and no required_scopes. Is there a way to allow the metaclass to see through this inheritance relationship?

在创建ScopedPermission类时,没有ReadJwtPermission类。解释器无法预测将来某个类将成为具有required_scopes属性的子类ScopedPermission。但是你可以做一些不同的事情

子类继承父类的元类。如果父类使用该元类,则每个子类都必须具有所需的属性。我还使用__new__在类创建之前检查该属性。以下是一个例子:

class Metaclass(type):
    def __new__(mcs, name, bases, attrs):

        # This condition skips Base class's requiement for having "required_scopes"
        # otherwise you should specify "required_scopes" for Base class as well.
        if name == 'Base':
            return super().__new__(mcs, 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}'

        # setting "has_permission attribute here"
        attrs['has_permission'] = mcs.has_permission()

        return super().__new__(mcs, name, bases, attrs)

    # I just removed the implementation so that I can be able to run this class.
    @staticmethod
    def has_permission():
        pass


class Base(metaclass=Metaclass):
    pass

class A(Base):
    required_scopes = ['read:jwt']

print(A.message)

输出:

Resource requires scope=read:jwt

但现在:

class B(Base):
    pass

这会引起错误

Traceback (most recent call last):
  File "< ->", line 9, in __new__
    required_scopes = attrs['required_scopes']
KeyError: 'required_scopes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "< ->", line 34, in <module>
    class B(Base):
  File "< ->", line 11, in __new__
    raise TypeError(f'{name} must include "required_scopes" attribute.')
TypeError: B must include "required_scopes" attribute.

相关问题 更多 >