新增头像接口:POST /profiles/me/avatar 上传、DELETE /profiles/me/avatar 删除
This commit is contained in:
+34
-1
@@ -1,7 +1,8 @@
|
||||
import math
|
||||
import uuid
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, File, HTTPException, Query, UploadFile, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import joinedload
|
||||
@@ -10,6 +11,7 @@ from app.deps import AdminUser, CurrentUser, DbSession, OptionalUser
|
||||
from app.models import Cloud, Profile, User, UserCollection
|
||||
from app.schemas import CloudOut, PageOut, ProfileOut, ProfileStatsOut, ProfileUpdateIn, PublicProfileOut
|
||||
from app.serializers import cloud_out, profile_out, public_profile_out
|
||||
from app.services.storage import delete_files, save_avatar
|
||||
|
||||
|
||||
router = APIRouter(prefix="/profiles", tags=["用户资料"])
|
||||
@@ -38,6 +40,37 @@ async def update_my_profile(
|
||||
return profile_out(user.profile)
|
||||
|
||||
|
||||
@router.post("/me/avatar", response_model=ProfileOut)
|
||||
async def upload_avatar(
|
||||
image: Annotated[UploadFile, File()],
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ProfileOut:
|
||||
if user.profile.avatar_path:
|
||||
old_path = user.profile.avatar_path
|
||||
user.profile.avatar_path = None
|
||||
await db.commit()
|
||||
await delete_files([old_path])
|
||||
avatar_path = await save_avatar(image, user.id)
|
||||
user.profile.avatar_path = avatar_path
|
||||
await db.commit()
|
||||
return profile_out(user.profile)
|
||||
|
||||
|
||||
@router.delete("/me/avatar", response_model=ProfileOut)
|
||||
async def delete_avatar(
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
) -> ProfileOut:
|
||||
if not user.profile.avatar_path:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="没有头像")
|
||||
old_path = user.profile.avatar_path
|
||||
user.profile.avatar_path = None
|
||||
await db.commit()
|
||||
await delete_files([old_path])
|
||||
return profile_out(user.profile)
|
||||
|
||||
|
||||
@router.get("/{user_id}/stats", response_model=ProfileStatsOut)
|
||||
async def get_user_stats(
|
||||
user_id: uuid.UUID,
|
||||
|
||||
Reference in New Issue
Block a user