PaiGram/utils/service/manager.py

69 lines
2.4 KiB
Python
Raw Normal View History

2022-07-26 10:07:31 +00:00
import inspect
2022-08-11 13:18:12 +00:00
from typing import List, Dict
2022-07-26 10:07:31 +00:00
from logger import Log
from models.types import Func
2022-07-26 10:07:31 +00:00
from utils.aiobrowser import AioBrowser
2022-08-11 13:18:12 +00:00
from utils.manager import ModulesManager
2022-07-26 10:07:31 +00:00
from utils.mysql import MySQL
from utils.redisdb import RedisDB
ServicesFunctions: List[Func] = []
ServicesDict: Dict[str, Func] = {}
2022-07-26 10:07:31 +00:00
def listener_service():
"""监听服务"""
def decorator(func: Func):
ServicesFunctions.append(
2022-07-26 10:07:31 +00:00
func
)
return func
return decorator
2022-08-11 13:18:12 +00:00
class ServicesManager(ModulesManager):
2022-07-26 10:07:31 +00:00
def __init__(self, mysql: MySQL, redis: RedisDB, browser: AioBrowser):
2022-08-11 13:18:12 +00:00
super().__init__()
2022-07-26 10:07:31 +00:00
self.browser = browser
self.redis = redis
self.mysql = mysql
self.services_list: List[str] = []
2022-07-26 10:07:31 +00:00
self.exclude_list: List[str] = []
2022-08-11 13:18:12 +00:00
self.manager_name = "核心服务管理器"
2022-07-26 10:07:31 +00:00
def add_service(self):
for func in ServicesFunctions:
2022-07-26 10:07:31 +00:00
if callable(func):
kwargs = {}
try:
signature = inspect.signature(func)
except ValueError as exception:
if "no signature found" in str(exception):
Log.warning("no signature found", exception)
break
elif "not supported by signature" in str(exception):
Log.warning("not supported by signature", exception)
break
else:
raise exception
else:
for parameter_name, parameter in signature.parameters.items():
annotation = parameter.annotation
if issubclass(annotation, MySQL):
kwargs[parameter_name] = self.mysql
if issubclass(annotation, RedisDB):
kwargs[parameter_name] = self.redis
if issubclass(annotation, AioBrowser):
kwargs[parameter_name] = self.browser
try:
handlers_list = func(**kwargs)
class_name = handlers_list.__class__.__name__
ServicesDict.setdefault(class_name, handlers_list)
except BaseException as exc:
2022-07-26 10:07:31 +00:00
Log.error("初始化Service失败", exc)
finally:
pass