Initial commit: MyBlog full stack blog
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
FastAPI 应用入口。
|
||||
|
||||
严格遵守全局架构,本文件只负责:
|
||||
1. 创建 FastAPI 实例
|
||||
2. 注册路由(router)
|
||||
3. 统一全局异常返回格式({success, data, message})
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .routers import api_router
|
||||
from .schemas import UnifiedResponse
|
||||
|
||||
# 创建 FastAPI 实例
|
||||
app = FastAPI(
|
||||
title="MyBlog API",
|
||||
description="个人博客系统后端 API(FastAPI + SQLite + JWT)",
|
||||
version="0.1.0",
|
||||
)
|
||||
|
||||
|
||||
def _unified_error(status_code: int, message: str) -> JSONResponse:
|
||||
"""构造符合全局统一格式的错误响应。"""
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=UnifiedResponse(success=False, data=None, message=message).model_dump(),
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
"""统一 HTTP 异常(业务错误)的返回格式。"""
|
||||
return _unified_error(exc.status_code, str(exc.detail))
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
"""统一请求参数校验错误的返回格式。"""
|
||||
return _unified_error(422, "请求参数校验失败")
|
||||
|
||||
|
||||
# 注册路由:后续任务在 routers 包中实现各业务路由后统一挂载
|
||||
app.include_router(api_router)
|
||||
Reference in New Issue
Block a user