Refactor config, logging, and startup structure
Introduced pkg modules for environment config, logging, and startup initialization. Replaced direct config and logging setup in main.py with modularized functions. Updated database and migration modules to use environment variables and improved DEBUG handling. Removed tool.py and migrated password utilities to pkg. Cleaned up legacy comments and unused code in models and routes.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
# ~/models/database.py
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncGenerator
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
@@ -9,11 +11,17 @@ from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from .migration import migration
|
||||
|
||||
ASYNC_DATABASE_URL = "sqlite+aiosqlite:///data.db"
|
||||
# 加载环境变量
|
||||
load_dotenv('.env')
|
||||
|
||||
# 获取 DEBUG 配置
|
||||
DEBUG = os.getenv("DEBUG", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
ASYNC_DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///data.db")
|
||||
|
||||
engine: AsyncEngine = create_async_engine(
|
||||
ASYNC_DATABASE_URL,
|
||||
echo=True,
|
||||
echo=DEBUG, # 根据 DEBUG 配置决定是否输出 SQL 日志
|
||||
connect_args={
|
||||
"check_same_thread": False
|
||||
} if ASYNC_DATABASE_URL.startswith("sqlite") else {},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from loguru import logger
|
||||
from sqlmodel import select
|
||||
from .setting import Setting
|
||||
from pkg.password import Password
|
||||
from pkg import Password
|
||||
|
||||
default_settings: list[Setting] = [
|
||||
Setting(type='string', name='version', value='1.0.0'),
|
||||
@@ -33,56 +33,4 @@ async def migration(session):
|
||||
to_insert = [s for s in settings if s.name not in existed]
|
||||
if to_insert:
|
||||
# 使用你写好的通用新增方法(是类方法),并传入会话
|
||||
await Setting.add(session, to_insert, refresh=False)
|
||||
|
||||
"""
|
||||
# 初始化设置表数据
|
||||
async with db.execute("SELECT name FROM fr_settings WHERE name = 'version'") as cursor:
|
||||
if not await cursor.fetchone():
|
||||
await db.execute(
|
||||
"INSERT INTO fr_settings (type, name, value) VALUES (?, ?, ?)",
|
||||
('string', 'version', '1.0.0')
|
||||
)
|
||||
logging.info("插入初始版本信息: version 1.0.0")
|
||||
|
||||
async with db.execute("SELECT name FROM fr_settings WHERE name = 'ver'") as cursor:
|
||||
if not await cursor.fetchone():
|
||||
await db.execute(
|
||||
"INSERT INTO fr_settings (type, name, value) VALUES (?, ?, ?)",
|
||||
('int', 'ver', '1')
|
||||
)
|
||||
logging.info("插入初始版本号: ver 1")
|
||||
|
||||
async with db.execute("SELECT name FROM fr_settings WHERE name = 'account'") as cursor:
|
||||
if not await cursor.fetchone():
|
||||
account = 'admin@yuxiaoqiu.cn'
|
||||
await db.execute(
|
||||
"INSERT INTO fr_settings (type, name, value) VALUES (?, ?, ?)",
|
||||
('string', 'account', account)
|
||||
)
|
||||
logging.info(f"插入初始账号信息: {account}")
|
||||
print(f"账号: {account}")
|
||||
|
||||
async with db.execute("SELECT name FROM fr_settings WHERE name = 'password'") as cursor:
|
||||
if not await cursor.fetchone():
|
||||
password = tool.generate_password()
|
||||
hashed_password = tool.hash_password(password)
|
||||
await db.execute(
|
||||
"INSERT INTO fr_settings (type, name, value) VALUES (?, ?, ?)",
|
||||
('string', 'password', hashed_password)
|
||||
)
|
||||
logging.info("插入初始密码信息")
|
||||
print(f"密码(请牢记,后续不再显示): {password}")
|
||||
|
||||
async with db.execute("SELECT name FROM fr_settings WHERE name = 'SECRET_KEY'") as cursor:
|
||||
if not await cursor.fetchone():
|
||||
secret_key = tool.generate_password(64)
|
||||
await db.execute(
|
||||
"INSERT INTO fr_settings (type, name, value) VALUES (?, ?, ?)",
|
||||
('string', 'SECRET_KEY', secret_key)
|
||||
)
|
||||
logging.info("插入初始密钥信息")
|
||||
|
||||
await db.commit()
|
||||
logging.info("数据库初始化完成并提交更改")
|
||||
"""
|
||||
await Setting.add(session, to_insert, refresh=False)
|
||||
@@ -1,5 +1,3 @@
|
||||
# my_project/models/download.py
|
||||
|
||||
from typing import Literal
|
||||
from sqlmodel import Field, Column, String, DateTime
|
||||
from .base import TableBase, IdMixin
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
# model/setting.py
|
||||
from sqlmodel import Field
|
||||
from .base import TableBase
|
||||
|
||||
"""
|
||||
原表:
|
||||
CREATE TABLE IF NOT EXISTS fr_settings (
|
||||
type TEXT,
|
||||
name TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
)
|
||||
"""
|
||||
|
||||
class Setting(TableBase, table=True):
|
||||
|
||||
type: str = Field(index=True, nullable=False, description="设置类型")
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
from pydantic import BaseModel
|
||||
from passlib.context import CryptContext
|
||||
|
||||
# FastAPI 鉴权模型
|
||||
# FastAPI authentication model
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
class TokenData(BaseModel):
|
||||
username: str | None = None
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
username: str | None = None
|
||||
Reference in New Issue
Block a user