ashleysommer / sanic-plugin-toolkit

Easily create Plugins for Sanic!
MIT License
51 stars 9 forks source link

Attributeerror: registration error occurred while registering the plug-in #21

Closed Hillsir closed 3 years ago

Hillsir commented 3 years ago

The following error occurred when I registered the plug-in. I don't know where the problem is. I have written a plug-in using SPT. It runs normally, but now the error is very strange

Traceback (most recent call last):
  File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/wang/.vscode/extensions/ms-python.python-2021.5.926500501/pythonFiles/lib/python/debugpy/__main__.py", line 45, in <module>
    cli.main()
  File "/home/wang/.vscode/extensions/ms-python.python-2021.5.926500501/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 444, in main
    run()
  File "/home/wang/.vscode/extensions/ms-python.python-2021.5.926500501/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 285, in run_file
    runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
  File "/usr/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/usr/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/wang/code/python/Test/srf-project-template/run.py", line 16, in <module>
    from apps import app
  File "/home/wang/code/python/Test/srf-project-template/apps/__init__.py", line 49, in <module>
    app = create_app()
  File "/home/wang/code/python/Test/srf-project-template/apps/__init__.py", line 41, in create_app
    realm.register_plugin(srf_cache)
  File "/home/wang/code/venv/dev_srf/lib/python3.7/site-packages/sanic_plugin_toolkit/realm.py", line 203, in register_plugin
    if plugin.is_registered_in_realm(self):
  File "/home/wang/code/venv/dev_srf/lib/python3.7/site-packages/sanic_plugin_toolkit/plugin.py", line 427, in is_registered_in_realm
    for reg in self.registrations:
AttributeError: registrations

code run.py

def create_app():
    """工厂函数"""
    sanic_app = Sanic(name='')
    sanic_app.update_config(Path.cwd() / cofing_name)
    realm = SanicPluginRealm(sanic_app)
    realm.register_plugin(cors) # ok
    realm.register_plugin(apps_helper) # ok 
    realm.register_plugin(srf_cache) # error
    register_tortoise(
        sanic_app, db_url=sanic_app.config.get('DB_CONNECT_STR'), modules=apps_helper.models
        # , generate_schemas=False
    )
    return sanic_app

code plug.py

class Cache(SanicPlugin, metaclass=SingletonMeta):

    def __init__(self, *args, **kwargs):
        self._caches = ObjectDict()
        self._current_cache = None

        self.connections = ObjectDict()
        self._external_connections = ObjectDict()

    def on_registered(self, context, reg, *args, **kwargs):
        self.init_app(context, *args, **kwargs)

    def get_config(self, app):
        app_config = app.config
        if CACGE_CONFIG_KEY not in app_config:
            raise TypeError("Sanic config not '%s' value" % CACGE_CONFIG_KEY)
        config = app_config.get(CACGE_CONFIG_KEY)
        if not isinstance(config, dict):
            raise TypeError("Sanic config '%s' value must be a dict type" % CACGE_CONFIG_KEY)
        return config

    def init_db(self, app, engines):

        @app.listener('before_server_start')
        async def aredis_configure(_app, loop):
            for name, config in engines.items():
                engine_module = config['engine_module']
                db_config = config['db_config']
                external = config['external']
                if not engine_module.has_db:
                    self._caches[name] = engine_module(connection)
                    continue
                connection = engine_module._create_connection(db_config)
                client_name = name.lower()
                self.connections[client_name] = connection
                self._caches[name] = engine_module(connection)
                if external:
                    self._external_connections[client_name] = connection
            setattr(_app, 'cache_db_conn', self._external_connections)

        @app.listener('after_server_stop')
        async def close_redis(_app, _loop):
            for engine in engines.values():
                engine._disconnect_connection()

    def init_app(self, context, *args, **kwargs):
        app = context.app
        self.config = self.get_config(app=app)
        engine_list = {}
        for name, config in self.config:
            engine_module_path = config.get('engine')
            engine_module = import_modul_by_str(engine_module_path)
            db_config = config.get('db_config')
            external = config.get('external')
            engine_list[name] = {
                'engine_module': engine_module,
                'db_config': db_config,
                'external': external

            }

        self.init_db(app, engine_list)

    def select(self, name):
        if name in self.all_caches:
            cache = self.all_caches[name]
            self.current_cache = cache
            return cache
        raise CacheNoFoundEXC()

    @property
    def current_cache(self):
        if self._current_cache is None:
            self._current_cache = self.all_caches
        return self._current_cache

    @property
    def all_caches(self):
        return self._caches
Hillsir commented 3 years ago

Problems found, not inherited super().__init__()