reconstruct config module

This commit is contained in:
felinae98
2022-03-13 16:38:12 +08:00
parent 17c3d0c667
commit 7affe27316
14 changed files with 539 additions and 74 deletions
+1 -5
View File
@@ -1,7 +1,7 @@
import nonebot
from nonebot.adapters.onebot.v11.bot import Bot
from ..config import Config, NoSuchSubscribeException, NoSuchUserException
from ..config import NoSuchSubscribeException, NoSuchUserException, config
from ..platform import check_sub_target, platform_manager
from .jwt import pack_jwt
from .token_manager import token_manager
@@ -83,7 +83,6 @@ async def get_subs_info(jwt_obj: dict):
res = {}
for group in groups:
group_id = group["id"]
config = Config()
subs = list(
map(
lambda sub: {
@@ -112,7 +111,6 @@ async def add_group_sub(
cats: list[int],
tags: list[str],
):
config = Config()
config.add_subscribe(
int(group_number), "group", target, target_name, platform_name, cats, tags
)
@@ -120,7 +118,6 @@ async def add_group_sub(
async def del_group_sub(group_number: str, platform_name: str, target: str):
config = Config()
try:
config.del_subscribe(int(group_number), "group", target, platform_name)
except (NoSuchUserException, NoSuchSubscribeException):
@@ -136,7 +133,6 @@ async def update_group_sub(
cats: list[int],
tags: list[str],
):
config = Config()
try:
config.update_subscribe(
int(group_number), "group", target, target_name, platform_name, cats, tags
@@ -0,0 +1 @@
from .config_legacy import NoSuchSubscribeException, NoSuchUserException, config
@@ -7,10 +7,10 @@ import nonebot
from nonebot.log import logger
from tinydb import Query, TinyDB
from .platform import platform_manager
from .plugin_config import plugin_config
from .types import Target, User
from .utils import Singleton
from ..platform import platform_manager
from ..plugin_config import plugin_config
from ..types import Target, User
from ..utils import Singleton
supported_target_type = platform_manager.keys()
@@ -241,3 +241,5 @@ def start_up():
nonebot.get_driver().on_startup(start_up)
config = Config()
@@ -0,0 +1,37 @@
from sqlalchemy.orm import declarative_base, relationship
from sqlalchemy.orm.decl_api import DeclarativeMeta
from sqlalchemy.sql.schema import Column, ForeignKey
from sqlalchemy.sql.sqltypes import Integer, String
class Base(metaclass=DeclarativeMeta):
__abstract__ = True
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True, autoincrement=True)
type = Column(String(20), nullable=False)
uid = Column(Integer, nullable=False)
class Target(Base):
__tablename__ = "target"
id = Column(Integer, primary_key=True, autoincrement=True)
platform_name = Column(String(20), nullable=False)
target = Column(String(1024), nullable=False)
target_name = Column(String(1024), nullable=False)
class Subscribe(Base):
__tablename__ = "subscribe"
target_id = Column(Integer, ForeignKey(Target.id))
user_id = Column(Integer, ForeignKey(User.id))
categories = Column(String(1024))
tags = Column(String(1024))
target = relationship("Target")
user = relationship("User")
@@ -0,0 +1 @@
Generic single-database configuration.
@@ -0,0 +1,73 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
+2 -8
View File
@@ -1,5 +1,4 @@
import asyncio
from asyncio.tasks import Task
from datetime import datetime
from typing import Optional, Type
@@ -12,12 +11,11 @@ from nonebot.internal.params import ArgStr
from nonebot.internal.rule import Rule
from nonebot.log import logger
from nonebot.matcher import Matcher
from nonebot.params import Depends, EventMessage, EventPlainText, EventToMe
from nonebot.params import Depends, EventPlainText, EventToMe
from nonebot.permission import SUPERUSER
from nonebot.rule import to_me
from nonebot.typing import T_State
from .config import Config
from .config import config
from .platform import check_sub_target, platform_manager
from .plugin_config import plugin_config
from .types import Category, Target, User
@@ -166,7 +164,6 @@ def do_add_sub(add_sub: Type[Matcher]):
@add_sub.got("tags", _gen_prompt_template("{_prompt}"), [Depends(parser_tags)])
async def add_sub_process(event: Event, state: T_State):
config = Config()
user = state.get("target_user_info")
assert isinstance(user, User)
config.add_subscribe(
@@ -188,7 +185,6 @@ def do_query_sub(query_sub: Type[Matcher]):
@query_sub.handle()
async def _(state: T_State):
config: Config = Config()
user_info = state["target_user_info"]
assert isinstance(user_info, User)
sub_list = config.list_subscribe(
@@ -219,7 +215,6 @@ def do_del_sub(del_sub: Type[Matcher]):
@del_sub.handle()
async def send_list(bot: Bot, event: Event, state: T_State):
config: Config = Config()
user_info = state["target_user_info"]
assert isinstance(user_info, User)
sub_list = config.list_subscribe(
@@ -254,7 +249,6 @@ def do_del_sub(del_sub: Type[Matcher]):
async def do_del(event: Event, state: T_State):
try:
index = int(str(event.get_message()).strip())
config = Config()
user_info = state["target_user_info"]
assert isinstance(user_info, User)
config.del_subscribe(
+1 -2
View File
@@ -6,7 +6,7 @@ from nonebot import get_driver
from nonebot.adapters.onebot.v11.bot import Bot
from nonebot.log import LoguruHandler, logger
from .config import Config
from .config import config
from .platform import platform_manager
from .plugin_config import plugin_config
from .send import do_send_msgs, send_msgs
@@ -25,7 +25,6 @@ async def _start():
async def fetch_and_send(target_type: str):
config = Config()
target = config.get_next_target(target_type)
if not target:
return