Step 12:后端轻量优化(API 稳定性 & 前端友好)

This commit is contained in:
Cheng Zhou
2025-12-16 20:03:05 +08:00
parent a54d7faf19
commit 5eab324c50
44 changed files with 161 additions and 14 deletions
+7 -4
View File
@@ -5,6 +5,7 @@ from fastapi import Depends, HTTPException, status
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.exceptions import AppException
from app.core.security import decode_token, oauth2_scheme
from app.crud import user as user_crud
from app.crud import member as member_crud
@@ -75,9 +76,10 @@ def require_study_member():
return current_user
membership = await member_crud.get_member(db, study_id, current_user.id)
if not membership or not membership.is_active:
raise HTTPException(
raise AppException(
code="FORBIDDEN",
message="Not a member of this study",
status_code=status.HTTP_403_FORBIDDEN,
detail="Not a member of this study",
)
return current_user
@@ -96,9 +98,10 @@ def require_study_roles(roles: Iterable[str]):
return current_user
membership = await member_crud.get_member(db, study_id, current_user.id)
if not membership or not membership.is_active or membership.role_in_study not in roles_set:
raise HTTPException(
raise AppException(
code="FORBIDDEN",
message="Insufficient study permissions",
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient study permissions",
)
return current_user
+19
View File
@@ -0,0 +1,19 @@
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
class AppException(Exception):
def __init__(self, code: str, message: str, status_code: int = status.HTTP_400_BAD_REQUEST):
self.code = code
self.message = message
self.status_code = status_code
super().__init__(message)
def register_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(AppException)
async def app_exception_handler(_: Request, exc: AppException) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={"code": exc.code, "message": exc.message},
)