fastapi-template/main.py

59 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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_async_sqlalchemy import SQLAlchemyMiddleware
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(SQLAlchemyMiddleware, db_url=mysql_config.async_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()