mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-24 13:37:13 +00:00
重构代码生成模块,删除冗余文件并优化结构: 1. 删除旧的form、page、table等相关文件 2. 新增gencode模块基础结构 3. 移动jinja2工具类和模板引擎初始化器到utils目录 4. 优化数据库模型关系定义 5. 更新nginx配置支持WebSocket 6. 添加正则验证和加密工具类 7. 修复菜单和部门模型的循环引用问题 8. 优化初始化脚本和配置加载逻辑 调整初始化流程,使用统一会话管理: 1. 修改数据库初始化使用AsyncSessionLocal 2. 优化定时任务初始化逻辑 3. 统一配置和字典服务初始化方式 4. 修复模型关系定义导致的循环导入问题 其他改进: 1. 更新requirements.txt添加依赖 2. 调整IP白名单配置 3. 优化数据库连接日志输出 4. 修复模型继承关系问题
127 lines
4.3 KiB
Python
127 lines
4.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
from redis import asyncio as aioredis
|
|
from motor.motor_asyncio import AsyncIOMotorClient
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import create_engine, Engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.ext.asyncio import (
|
|
create_async_engine,
|
|
async_sessionmaker,
|
|
AsyncSession,
|
|
AsyncEngine
|
|
)
|
|
|
|
from app.core.logger import logger
|
|
from app.config.setting import settings
|
|
from app.core.exceptions import CustomException
|
|
from app.core.base_model import MappedBase
|
|
|
|
# 同步数据库引擎
|
|
engine: Engine = create_engine(
|
|
url=settings.DB_URI,
|
|
echo=settings.DATABASE_ECHO,
|
|
pool_pre_ping=settings.POOL_PRE_PING,
|
|
pool_recycle=settings.POOL_RECYCLE,
|
|
)
|
|
# 同步数据库会话工厂
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 异步数据库引擎
|
|
async_engine: AsyncEngine = create_async_engine(
|
|
url=settings.ASYNC_DB_URI,
|
|
echo=settings.DATABASE_ECHO,
|
|
echo_pool=settings.ECHO_POOL,
|
|
pool_pre_ping=settings.POOL_PRE_PING,
|
|
future=settings.FUTURE,
|
|
pool_recycle=settings.POOL_RECYCLE,
|
|
# pool_size=settings.POOL_SIZE, # sqlite 不支持
|
|
# max_overflow=settings.MAX_OVERFLOW, # sqlite 不支持
|
|
# pool_timeout=settings.POOL_TIMEOUT, # sqlite 不支持
|
|
)
|
|
|
|
# 异步数据库会话工厂
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
bind=async_engine,
|
|
autocommit=settings.AUTOCOMMIT,
|
|
autoflush=settings.AUTOFETCH,
|
|
expire_on_commit=settings.EXPIRE_ON_COMMIT,
|
|
class_=AsyncSession
|
|
)
|
|
|
|
def session_connect() -> AsyncSession:
|
|
"""获取数据库会话"""
|
|
try:
|
|
if not settings.SQL_DB_ENABLE:
|
|
raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE")
|
|
return AsyncSessionLocal()
|
|
except Exception as e:
|
|
raise CustomException(msg=f"数据库连接失败: {e}")
|
|
|
|
async def init_create_table():
|
|
"""
|
|
应用启动时初始化数据库连接
|
|
|
|
:return:
|
|
"""
|
|
try:
|
|
async with async_engine.begin() as conn:
|
|
await conn.run_sync(MappedBase.metadata.create_all)
|
|
except Exception as e:
|
|
raise CustomException(msg=f"数据库连接失败: {e}")
|
|
|
|
async def redis_connect(app: FastAPI, status: bool) -> aioredis.Redis:
|
|
"""创建或关闭Redis连接"""
|
|
if not settings.REDIS_ENABLE:
|
|
raise CustomException(msg="请先开启Redis连接", data="请启用 app/core/config.py: REDIS_ENABLE")
|
|
|
|
if status:
|
|
try:
|
|
|
|
rd = await aioredis.from_url(
|
|
url=settings.REDIS_URI,
|
|
encoding='utf-8',
|
|
decode_responses=True,
|
|
health_check_interval=20,
|
|
max_connections=settings.POOL_SIZE,
|
|
socket_timeout=settings.POOL_TIMEOUT
|
|
)
|
|
app.state.redis = rd
|
|
if await rd.ping():
|
|
logger.info("Redis连接成功...")
|
|
return rd
|
|
raise CustomException(msg="Redis连接失败")
|
|
except aioredis.AuthenticationError as e:
|
|
raise aioredis.AuthenticationError(f"Redis认证失败: {e}")
|
|
except aioredis.TimeoutError as e:
|
|
raise aioredis.TimeoutError(f"Redis连接超时: {e}")
|
|
except aioredis.RedisError as e:
|
|
raise aioredis.RedisError(f"Redis连接错误: {e}")
|
|
else:
|
|
await app.state.redis.close()
|
|
logger.info('Redis连接已关闭')
|
|
|
|
async def mongodb_connect(app: FastAPI, status: bool) -> AsyncIOMotorClient:
|
|
"""创建或关闭MongoDB连接"""
|
|
if not settings.MONGO_DB_ENABLE:
|
|
raise CustomException(msg="请先开启MongoDB连接", data="请启用 app/core/config.py: MONGO_DB_ENABLE")
|
|
|
|
if status:
|
|
try:
|
|
|
|
client = AsyncIOMotorClient(
|
|
settings.MONGO_DB_URI,
|
|
maxPoolSize=settings.POOL_SIZE,
|
|
minPoolSize=settings.MAX_OVERFLOW,
|
|
serverSelectionTimeoutMS=settings.POOL_TIMEOUT * 1000
|
|
)
|
|
app.state.mongo_client = client
|
|
app.state.mongo = client[settings.MONGO_DB_NAME]
|
|
data = await client.server_info()
|
|
logger.info("MongoDB连接成功...", data)
|
|
return data
|
|
except Exception as e:
|
|
raise ValueError(f"MongoDB连接失败: {e}")
|
|
else:
|
|
app.state.mongo_client.close()
|
|
logger.info("MongoDB连接已关闭") |