fix 数据库连接复用

This commit is contained in:
jxxghp 2023-08-22 08:13:44 +08:00
parent a202b5efdd
commit 781de29591
10 changed files with 57 additions and 40 deletions

View File

@ -12,6 +12,7 @@ from app.chain.transfer import TransferChain
from app.core.event import Event as ManagerEvent from app.core.event import Event as ManagerEvent
from app.core.event import eventmanager, EventManager from app.core.event import eventmanager, EventManager
from app.core.plugin import PluginManager from app.core.plugin import PluginManager
from app.db import SessionLocal
from app.log import logger from app.log import logger
from app.schemas.types import EventType, MessageChannel from app.schemas.types import EventType, MessageChannel
from app.utils.object import ObjectUtils from app.utils.object import ObjectUtils
@ -38,6 +39,8 @@ class Command(metaclass=Singleton):
_event = Event() _event = Event()
def __init__(self): def __init__(self):
# 数据库连接
self._db = SessionLocal()
# 事件管理器 # 事件管理器
self.eventmanager = EventManager() self.eventmanager = EventManager()
# 插件管理器 # 插件管理器
@ -45,67 +48,67 @@ class Command(metaclass=Singleton):
# 内置命令 # 内置命令
self._commands = { self._commands = {
"/cookiecloud": { "/cookiecloud": {
"func": CookieCloudChain().remote_sync, "func": CookieCloudChain(self._db).remote_sync,
"description": "同步站点", "description": "同步站点",
"data": {} "data": {}
}, },
"/sites": { "/sites": {
"func": SiteChain().remote_list, "func": SiteChain(self._db).remote_list,
"description": "查询站点", "description": "查询站点",
"data": {} "data": {}
}, },
"/site_cookie": { "/site_cookie": {
"func": SiteChain().remote_cookie, "func": SiteChain(self._db).remote_cookie,
"description": "更新站点Cookie", "description": "更新站点Cookie",
"data": {} "data": {}
}, },
"/site_enable": { "/site_enable": {
"func": SiteChain().remote_enable, "func": SiteChain(self._db).remote_enable,
"description": "启用站点", "description": "启用站点",
"data": {} "data": {}
}, },
"/site_disable": { "/site_disable": {
"func": SiteChain().remote_disable, "func": SiteChain(self._db).remote_disable,
"description": "禁用站点", "description": "禁用站点",
"data": {} "data": {}
}, },
"/mediaserver_sync": { "/mediaserver_sync": {
"func": MediaServerChain().remote_sync, "func": MediaServerChain(self._db).remote_sync,
"description": "同步媒体服务器", "description": "同步媒体服务器",
"data": {} "data": {}
}, },
"/subscribes": { "/subscribes": {
"func": SubscribeChain().remote_list, "func": SubscribeChain(self._db).remote_list,
"description": "查询订阅", "description": "查询订阅",
"data": {} "data": {}
}, },
"/subscribe_refresh": { "/subscribe_refresh": {
"func": SubscribeChain().remote_refresh, "func": SubscribeChain(self._db).remote_refresh,
"description": "刷新订阅", "description": "刷新订阅",
"data": {} "data": {}
}, },
"/subscribe_search": { "/subscribe_search": {
"func": SubscribeChain().remote_search, "func": SubscribeChain(self._db).remote_search,
"description": "搜索订阅", "description": "搜索订阅",
"data": {} "data": {}
}, },
"/subscribe_delete": { "/subscribe_delete": {
"func": SubscribeChain().remote_delete, "func": SubscribeChain(self._db).remote_delete,
"description": "删除订阅", "description": "删除订阅",
"data": {} "data": {}
}, },
"/downloading": { "/downloading": {
"func": DownloadChain().remote_downloading, "func": DownloadChain(self._db).remote_downloading,
"description": "正在下载", "description": "正在下载",
"data": {} "data": {}
}, },
"/transfer": { "/transfer": {
"func": TransferChain().process, "func": TransferChain(self._db).process,
"description": "下载文件整理", "description": "下载文件整理",
"data": {} "data": {}
}, },
"/redo": { "/redo": {
"func": TransferChain().remote_transfer, "func": TransferChain(self._db).remote_transfer,
"description": "手动整理", "description": "手动整理",
"data": {} "data": {}
} }
@ -123,7 +126,7 @@ class Command(metaclass=Singleton):
} }
) )
# 处理链 # 处理链
self.chain = CommandChian() self.chain = CommandChian(self._db)
# 广播注册命令菜单 # 广播注册命令菜单
self.chain.register_commands(commands=self.get_commands()) self.chain.register_commands(commands=self.get_commands())
# 消息处理线程 # 消息处理线程
@ -233,3 +236,7 @@ class Command(metaclass=Singleton):
args = " ".join(event_str.split()[1:]) args = " ".join(event_str.split()[1:])
if self.get(cmd): if self.get(cmd):
self.execute(cmd, args, event_channel, event_user) self.execute(cmd, args, event_channel, event_user)
def __del__(self):
if self._db:
self._db.close()

View File

@ -5,6 +5,7 @@ from typing import Any, List, Dict, Tuple
from app.chain import ChainBase from app.chain import ChainBase
from app.core.config import settings from app.core.config import settings
from app.core.event import EventManager from app.core.event import EventManager
from app.db import SessionLocal
from app.db.models import Base from app.db.models import Base
from app.db.plugindata_oper import PluginDataOper from app.db.plugindata_oper import PluginDataOper
from app.db.systemconfig_oper import SystemConfigOper from app.db.systemconfig_oper import SystemConfigOper
@ -37,10 +38,12 @@ class _PluginBase(metaclass=ABCMeta):
plugin_desc: str = "" plugin_desc: str = ""
def __init__(self): def __init__(self):
# 数据库连接
self.db = SessionLocal()
# 插件数据 # 插件数据
self.plugindata = PluginDataOper() self.plugindata = PluginDataOper(self.db)
# 处理链 # 处理链
self.chain = PluginChian() self.chain = PluginChian(self.db)
# 系统配置 # 系统配置
self.systemconfig = SystemConfigOper() self.systemconfig = SystemConfigOper()
# 系统消息 # 系统消息

View File

@ -62,7 +62,7 @@ class BestFilmVersion(_PluginBase):
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self._cache_path = settings.TEMP_PATH / "__best_film_version_cache__" self._cache_path = settings.TEMP_PATH / "__best_film_version_cache__"
self.subscribechain = SubscribeChain() self.subscribechain = SubscribeChain(self.db)
# 停止现有任务 # 停止现有任务
self.stop_service() self.stop_service()

View File

@ -90,9 +90,9 @@ class DirMonitor(_PluginBase):
tr = None tr = None
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self.transferhis = TransferHistoryOper() self.transferhis = TransferHistoryOper(self.db)
self.downloadhis = DownloadHistoryOper() self.downloadhis = DownloadHistoryOper(self.db)
self.transferchian = TransferChain() self.transferchian = TransferChain(self.db)
# 清空配置 # 清空配置
self._dirconf = {} self._dirconf = {}

View File

@ -65,8 +65,8 @@ class DoubanRank(_PluginBase):
_clearflag = False _clearflag = False
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self.downloadchain = DownloadChain() self.downloadchain = DownloadChain(self.db)
self.subscribechain = SubscribeChain() self.subscribechain = SubscribeChain(self.db)
if config: if config:
self._enabled = config.get("enabled") self._enabled = config.get("enabled")

View File

@ -66,9 +66,9 @@ class DoubanSync(_PluginBase):
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self.rsshelper = RssHelper() self.rsshelper = RssHelper()
self.downloadchain = DownloadChain() self.downloadchain = DownloadChain(self.db)
self.searchchain = SearchChain() self.searchchain = SearchChain(self.db)
self.subscribechain = SubscribeChain() self.subscribechain = SubscribeChain(self.db)
# 停止现有任务 # 停止现有任务
self.stop_service() self.stop_service()

View File

@ -61,7 +61,7 @@ class MediaSyncDel(_PluginBase):
tr = None tr = None
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self._transferhis = TransferHistoryOper() self._transferhis = TransferHistoryOper(self.db)
self.episode = Episode() self.episode = Episode()
self.qb = Qbittorrent() self.qb = Qbittorrent()
self.tr = Transmission() self.tr = Transmission()

View File

@ -51,9 +51,9 @@ class NAStoolSync(_PluginBase):
tr = None tr = None
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self._transferhistory = TransferHistoryOper() self._transferhistory = TransferHistoryOper(self.db)
self._plugindata = PluginDataOper() self._plugindata = PluginDataOper(self.db)
self._downloadhistory = DownloadHistoryOper() self._downloadhistory = DownloadHistoryOper(self.db)
if config: if config:
self._clear = config.get("clear") self._clear = config.get("clear")

View File

@ -70,9 +70,9 @@ class RssSubscribe(_PluginBase):
def init_plugin(self, config: dict = None): def init_plugin(self, config: dict = None):
self.rsshelper = RssHelper() self.rsshelper = RssHelper()
self.downloadchain = DownloadChain() self.downloadchain = DownloadChain(self.db)
self.searchchain = SearchChain() self.searchchain = SearchChain(self.db)
self.subscribechain = SubscribeChain() self.subscribechain = SubscribeChain(self.db)
# 停止现有任务 # 停止现有任务
self.stop_service() self.stop_service()

View File

@ -12,6 +12,7 @@ from app.chain.rss import RssChain
from app.chain.subscribe import SubscribeChain from app.chain.subscribe import SubscribeChain
from app.chain.transfer import TransferChain from app.chain.transfer import TransferChain
from app.core.config import settings from app.core.config import settings
from app.db import SessionLocal
from app.log import logger from app.log import logger
from app.utils.singleton import Singleton from app.utils.singleton import Singleton
from app.utils.timer import TimerUtils from app.utils.timer import TimerUtils
@ -38,12 +39,14 @@ class Scheduler(metaclass=Singleton):
}) })
def __init__(self): def __init__(self):
# 数据库连接
self._db = SessionLocal()
# 调试模式不启动定时服务 # 调试模式不启动定时服务
if settings.DEV: if settings.DEV:
return return
# CookieCloud定时同步 # CookieCloud定时同步
if settings.COOKIECLOUD_INTERVAL: if settings.COOKIECLOUD_INTERVAL:
self._scheduler.add_job(CookieCloudChain().process, self._scheduler.add_job(CookieCloudChain(self._db).process,
"interval", "interval",
minutes=settings.COOKIECLOUD_INTERVAL, minutes=settings.COOKIECLOUD_INTERVAL,
next_run_time=datetime.now(pytz.timezone(settings.TZ)) + timedelta(minutes=1), next_run_time=datetime.now(pytz.timezone(settings.TZ)) + timedelta(minutes=1),
@ -51,35 +54,35 @@ class Scheduler(metaclass=Singleton):
# 媒体服务器同步 # 媒体服务器同步
if settings.MEDIASERVER_SYNC_INTERVAL: if settings.MEDIASERVER_SYNC_INTERVAL:
self._scheduler.add_job(MediaServerChain().sync, "interval", self._scheduler.add_job(MediaServerChain(self._db).sync, "interval",
hours=settings.MEDIASERVER_SYNC_INTERVAL, hours=settings.MEDIASERVER_SYNC_INTERVAL,
next_run_time=datetime.now(pytz.timezone(settings.TZ)) + timedelta(minutes=5), next_run_time=datetime.now(pytz.timezone(settings.TZ)) + timedelta(minutes=5),
name="同步媒体服务器") name="同步媒体服务器")
# 新增订阅时搜索5分钟检查一次 # 新增订阅时搜索5分钟检查一次
self._scheduler.add_job(SubscribeChain().search, "interval", self._scheduler.add_job(SubscribeChain(self._db).search, "interval",
minutes=5, kwargs={'state': 'N'}) minutes=5, kwargs={'state': 'N'})
# 订阅状态每隔12小时搜索一次 # 订阅状态每隔12小时搜索一次
self._scheduler.add_job(SubscribeChain().search, "interval", self._scheduler.add_job(SubscribeChain(self._db).search, "interval",
hours=12, kwargs={'state': 'R'}, name="订阅搜索") hours=12, kwargs={'state': 'R'}, name="订阅搜索")
# 站点首页种子定时刷新缓存并匹配订阅 # 站点首页种子定时刷新缓存并匹配订阅
triggers = TimerUtils.random_scheduler(num_executions=30) triggers = TimerUtils.random_scheduler(num_executions=30)
for trigger in triggers: for trigger in triggers:
self._scheduler.add_job(SubscribeChain().refresh, "cron", self._scheduler.add_job(SubscribeChain(self._db).refresh, "cron",
hour=trigger.hour, minute=trigger.minute, name="订阅刷新") hour=trigger.hour, minute=trigger.minute, name="订阅刷新")
# 自定义订阅 # 自定义订阅
self._scheduler.add_job(RssChain().refresh, "interval", self._scheduler.add_job(RssChain(self._db).refresh, "interval",
minutes=30, name="自定义订阅刷新") minutes=30, name="自定义订阅刷新")
# 下载器文件转移每5分钟 # 下载器文件转移每5分钟
if settings.DOWNLOADER_MONITOR: if settings.DOWNLOADER_MONITOR:
self._scheduler.add_job(TransferChain().process, "interval", minutes=5, name="下载文件整理") self._scheduler.add_job(TransferChain(self._db).process, "interval", minutes=5, name="下载文件整理")
# 公共定时服务 # 公共定时服务
self._scheduler.add_job(SchedulerChain().scheduler_job, "interval", minutes=10) self._scheduler.add_job(SchedulerChain(self._db).scheduler_job, "interval", minutes=10)
# 打印服务 # 打印服务
logger.debug(self._scheduler.print_jobs()) logger.debug(self._scheduler.print_jobs())
@ -99,3 +102,7 @@ class Scheduler(metaclass=Singleton):
""" """
if self._scheduler.running: if self._scheduler.running:
self._scheduler.shutdown() self._scheduler.shutdown()
def __del__(self):
if self._db:
self._db.close()