我正在尝试使用注册模式(registry pattern)来注册所有我用 Flask-RESTFUL
定义的资源。
from flask_restful import Resource
class ResourceRegistry(type):
REGISTRY = {}
def __new__(cls, name, bases, attrs):
new_cls = type.__new__(cls, name, bases, attrs)
cls.REGISTRY[new_cls.__name__] = new_cls
return new_cls
@classmethod
def get_registry(cls):
return dict(cls.REGISTRY)
class BaseRegistered(object):
__metaclass__ = ResourceRegistry
class DefaultResource(BaseRegistered, Resource):
@classmethod
def get_resource_name(cls):
s = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', cls.__name__)
return '/' + re.sub('([a-z0-9])([A-Z])', r'\1-\2', s).lower()
当整个事情启动时,我会得到以下结果:
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
我尝试了使用代理类的层级,但结果仍然相同。那么有没有一种方法可以使用这种模式注册我的资源?