4e3a4b4602
带 Web 操作界面的备份系统,支持: - 数据源:MySQL 数据库(mysqldump)、服务器目录(tar.gz) - 存储目标:本地目录、S3 兼容对象存储(MinIO/Ceph/AWS S3) - 触发方式:手动 + Cron 定时调度(APScheduler) - 备份还原:MySQL 库、目录 - JWT 登录认证 + Fernet 字段加密 - 保留策略:按数量 + 按天数双重清理 技术栈:FastAPI + SQLAlchemy 2 + APScheduler + aioboto3; 前端 Vite + React 18 + TypeScript + Ant Design 5 + Zustand。 Docker Compose 一键起。 Co-Authored-By: Claude <noreply@anthropic.com>
60 lines
1.3 KiB
Python
60 lines
1.3 KiB
Python
"""SQLAlchemy 引擎与 Session 工厂。"""
|
|
from contextlib import contextmanager
|
|
from typing import Iterator
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
|
|
|
from app.config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
# SQLite 需要 check_same_thread=False(虽然我们用 FastAPI async/threadpool,但仍建议)
|
|
connect_args = {}
|
|
if settings.DATABASE_URL.startswith("sqlite"):
|
|
connect_args["check_same_thread"] = False
|
|
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
connect_args=connect_args,
|
|
pool_pre_ping=True,
|
|
future=True,
|
|
)
|
|
|
|
SessionLocal = sessionmaker(
|
|
bind=engine,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
expire_on_commit=False,
|
|
class_=Session,
|
|
)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
"""所有 ORM 模型的基类。"""
|
|
|
|
pass
|
|
|
|
|
|
def get_db() -> Iterator[Session]:
|
|
"""FastAPI 依赖:每次请求一个 Session。"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@contextmanager
|
|
def session_scope() -> Iterator[Session]:
|
|
"""普通上下文管理器版本,供非请求路径使用(如初始化、调度器)。"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
db.commit()
|
|
except Exception:
|
|
db.rollback()
|
|
raise
|
|
finally:
|
|
db.close()
|