52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
import logging.config as logging_config
|
|
import os
|
|
|
|
import fastapi_plugins
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.exceptions import HTTPException, RequestValidationError
|
|
from fastapi_sqlalchemy import DBSessionMiddleware
|
|
|
|
from config import init_config
|
|
from src.utils.exception import (http_exception_handler,
|
|
request_validation_error_handler)
|
|
|
|
|
|
def create_app():
|
|
app = FastAPI()
|
|
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
# 创建日志文件夹和临时文件上传文件夹
|
|
if not os.path.exists("files"):
|
|
os.mkdir("files")
|
|
# 日志配置
|
|
if os.getenv("FAST_API_ENV", "dev") == "prod":
|
|
if not os.path.exists("logs"):
|
|
os.mkdir("logs")
|
|
logging_config.fileConfig('conf/log.ini')
|
|
# 初始化配置文件
|
|
mysql_config, redis_config = init_config()
|
|
# 添加sqlalchemy数据库中间件
|
|
# once the middleware is applied, any route can then access the database session from the global ``db``
|
|
app.add_middleware(DBSessionMiddleware, db_url=mysql_config.sqlalchemy_db_uri)
|
|
# Redis 缓存初始化
|
|
await fastapi_plugins.redis_plugin.init_app(app, redis_config)
|
|
await fastapi_plugins.redis_plugin.init()
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
await fastapi_plugins.redis_plugin.terminate()
|
|
|
|
# 添加异常处理
|
|
app.add_exception_handler(HTTPException, http_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, request_validation_error_handler)
|
|
|
|
# 在这里添加API route
|
|
from src.api import test
|
|
app.include_router(test.router)
|
|
return app
|
|
|
|
|
|
fast_api_app = create_app()
|
|
|