AI-News/backend/app/main.py
2025-12-04 10:04:21 +08:00

59 lines
1.8 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.

# app/main.py (或你当前这个文件名)
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles # ✅ 新增:静态文件
from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware
from app.api.errors.http_error import http_error_handler
from app.api.errors.validation_error import http422_error_handler
from app.api.routes.api import router as api_router
from app.core.config import get_app_settings
from app.core.events import create_start_app_handler, create_stop_app_handler
def get_application() -> FastAPI:
settings = get_app_settings()
settings.configure_logging()
application = FastAPI(**settings.fastapi_kwargs)
application.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origin_regex=".*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
)
application.add_event_handler(
"startup",
create_start_app_handler(application, settings),
)
application.add_event_handler(
"shutdown",
create_stop_app_handler(application),
)
application.add_exception_handler(HTTPException, http_error_handler)
application.add_exception_handler(RequestValidationError, http422_error_handler)
# 所有业务 API 挂在 /api 前缀下(上传接口也在这里:/api/upload-image
application.include_router(api_router, prefix=settings.api_prefix)
# ✅ 静态资源:让 /static/... 可直接访问(封面、正文图片等)
application.mount(
"/static",
StaticFiles(directory="static"),
name="static",
)
return application
app = get_application()