change avatar (and other images) to relative path of s3 bucket

This commit is contained in:
2026-05-17 19:29:08 +08:00
parent 9748992135
commit 8940876694
3 changed files with 21 additions and 9 deletions
+3 -2
View File
@@ -7,6 +7,7 @@ from app.auth.deps import get_current_user
from app.db import SessionLocal from app.db import SessionLocal
from app.models import User from app.models import User
from app.auth.jwt import create_jwt_token, create_refresh_token, decode_token from app.auth.jwt import create_jwt_token, create_refresh_token, decode_token
from app.utils.format import get_image_url
router = APIRouter() router = APIRouter()
@@ -114,7 +115,7 @@ async def auth_callback(request: Request, code: str, state: str):
"user": { "user": {
"email": user.email, "email": user.email,
"name": user.name, "name": user.name,
"avatar": user.avatar, "avatar": get_image_url(user.avatar),
} }
} }
@@ -123,7 +124,7 @@ def me(user = Depends(get_current_user)):
return { return {
"email": user.email, "email": user.email,
"name": user.name, "name": user.name,
"avatar": user.avatar, "avatar": get_image_url(user.avatar),
} }
@router.post("/refresh") @router.post("/refresh")
+12
View File
@@ -0,0 +1,12 @@
import os
OSS_BASE_URL = os.getenv("OSS_BASE_URL", "").rstrip("/")
def get_image_url(path: str) -> str:
if not path:
return ""
# 如果已经是完整 URL (比如 Google 原图),直接返回
if path.startswith(("http://", "https://")):
return path
# 否则拼接 OSS 基础域名
return f"{OSS_BASE_URL}/{path}"
+6 -7
View File
@@ -38,13 +38,12 @@ async def upload_google_avatar_to_s3(google_avatar_url: str, user_id: str) -> st
# 在高并发下建议使用 run_in_executor,初期可以直接这样写 # 在高并发下建议使用 run_in_executor,初期可以直接这样写
bucket.put_object(object_name, image_data, headers=headers) bucket.put_object(object_name, image_data, headers=headers)
# 4. 生成公开访问的 URL # 不直接返回公开访问的 URL,而是返回 OSS 内部相对路径,前端可以通过 CDN 或后端代理访问
# 阿里云 OSS 标准 URL 格式: https://bucket-name.endpoint/object-name # 这样可以支持后续更换存储服务,以及更换 OSS_BASE_URL 域名而不影响前端
# 例如: https://character-roleplay-dev-asset.oss-ap-northeast-1.aliyuncs.com/avatars/xxx/avatar.jpg # host = ENDPOINT.replace("https://", "")
host = ENDPOINT.replace("https://", "") # oss_url = f"https://{BUCKET_NAME}.{host}/{object_name}"
oss_url = f"https://{BUCKET_NAME}.{host}/{object_name}" # return oss_url
return object_name
return oss_url
except Exception as e: except Exception as e:
# 打印错误日志,生产环境建议使用 logger # 打印错误日志,生产环境建议使用 logger