-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
57 lines (45 loc) · 1.73 KB
/
main.py
File metadata and controls
57 lines (45 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException
import logging
from core.config import get_settings
from core.logging import setup_logging
from core.route_scanner import scan_routers
from utils.response import CustomResponse
settings = get_settings()
# 初始化日志系统
setup_logging()
logger = logging.getLogger(__name__)
logger.info("Application starting...")
logger.debug(f"Current settings: {settings.json()}")
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
description=settings.DESCRIPTION,
docs_url="/docs" if settings.DEBUG else None,
redoc_url="/redoc" if settings.DEBUG else None,
)
# 设置CORS
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 全局扫描API路由
routers = scan_routers("api")
for router in routers:
app.include_router(router, prefix=settings.API_V1_STR)
# 全局异常处理
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return CustomResponse.error(message=exc.detail, status_code=exc.status_code)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return CustomResponse.error(message=str(exc), status_code=400)
@app.get("/")
async def root():
return CustomResponse.success(data={"message": "Welcome to Dify HTTP Service"})