66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
import logging.config as logging_config
|
||
import os
|
||
from contextlib import asynccontextmanager
|
||
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 authx.exceptions import AuthXException
|
||
from config import init_config
|
||
# from src.middleware.flask import flask_app
|
||
|
||
from src.utils.exception import http_exception_handler, request_validation_error_handler, authx_exception_handler
|
||
# 请求限制
|
||
import redis.asyncio as aio_redis
|
||
from fastapi_limiter import FastAPILimiter
|
||
|
||
|
||
def create_app():
|
||
mysql_config, redis_config = init_config()
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
# 创建日志文件夹和临时文件上传文件夹
|
||
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 缓存初始化
|
||
await fastapi_plugins.redis_plugin.init_app(app, redis_config)
|
||
await fastapi_plugins.redis_plugin.init()
|
||
# 请求限制
|
||
await FastAPILimiter.init(redis=aio_redis.from_url("redis://localhost:6379", encoding="utf8"))
|
||
yield
|
||
# 应用关闭时,关闭redis连接
|
||
await fastapi_plugins.redis_plugin.terminate()
|
||
await FastAPILimiter.close()
|
||
app = FastAPI(lifespan=lifespan)
|
||
# 添加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.add_exception_handler(HTTPException, http_exception_handler)
|
||
app.add_exception_handler(RequestValidationError, request_validation_error_handler)
|
||
# AuthX异常处理
|
||
app.add_exception_handler(AuthXException, authx_exception_handler)
|
||
|
||
|
||
# 可以在这里挂载Flask的应用,复用之前项目的相关代码
|
||
# app.mount("/v1", WSGIMiddleware(flask_app))
|
||
|
||
|
||
# 在这里添加API route
|
||
from src.api import example,auth_example
|
||
app.include_router(example.router, tags=["API示例"], prefix="/v1/example")
|
||
app.include_router(auth_example.router, tags=["认证示例"], prefix="/v1/auth_example")
|
||
return app
|
||
|
||
|
||
fast_api_app = create_app()
|
||
|