59 lines
2.0 KiB
Python
59 lines
2.0 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.middleware.wsgi import WSGIMiddleware
|
||
from fastapi_sqlalchemy import DBSessionMiddleware
|
||
|
||
from config import init_config
|
||
# from src.middleware.flask import flask_app
|
||
from src.utils.exception import (http_exception_handler,
|
||
request_validation_error_handler)
|
||
|
||
def create_app():
|
||
app = FastAPI()
|
||
|
||
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)
|
||
|
||
@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')
|
||
# 初始化配置文件
|
||
# Redis 缓存初始化
|
||
print(redis_config)
|
||
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)
|
||
|
||
# 可以在这里挂载Flask的应用,复用之前项目的相关代码
|
||
# app.mount("/v1", WSGIMiddleware(flask_app))
|
||
|
||
# 在这里添加API route
|
||
from src.api import example
|
||
app.include_router(example.router, tags=["API示例"], prefix="/example")
|
||
|
||
return app
|
||
|
||
|
||
fast_api_app = create_app()
|
||
|