56 lines
1.5 KiB
Python
56 lines
1.5 KiB
Python
# -*- coding = utf-8 -*-
|
|
# @Time : 2025/2/13 下午12:27
|
|
# @File : app.py
|
|
# @Software : PyCharm
|
|
# @Author : xingc
|
|
# @Desc :
|
|
import logging
|
|
|
|
from fastapi import FastAPI, Request, Response
|
|
|
|
from config import settings
|
|
from core.routers import routers
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def exception_log(request: Request, exc):
|
|
logger.error('\n'.join([
|
|
'',
|
|
f'request method: {request.method}',
|
|
f'request path: {request.path_params}',
|
|
f'request host: {request.client.host}',
|
|
f'query parameters: {dict(request.query_params)}',
|
|
f'abnormal description: {exc}',
|
|
]))
|
|
logger.exception(exc)
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
app = FastAPI(
|
|
debug=settings.DEBUG,
|
|
openapi_url='/openapi.json' if settings.DEBUG else None,
|
|
)
|
|
|
|
for router in routers:
|
|
app.include_router(router)
|
|
|
|
if settings.ENVIRONMENT != 'prod':
|
|
from fastapi.staticfiles import StaticFiles
|
|
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
|
|
|
@app.on_event('startup')
|
|
async def startup_event():
|
|
logger.info(f'Application <<{settings.NAME}>> is started')
|
|
|
|
@app.on_event('shutdown')
|
|
async def shutdown_event():
|
|
logger.info(f'Application <<{settings.NAME}>> is closed')
|
|
|
|
# @app.exception_handler(Exception)
|
|
# async def http_exception_handler(request: Request, exc: Exception):
|
|
# await exception_log(request, exc)
|
|
# return base_response.error(status_code=500, message='Server error')
|
|
|
|
return app
|