From 8940876694407369ae218a4a6fe0a392c5f479d7 Mon Sep 17 00:00:00 2001 From: Zayden Jung Date: Sun, 17 May 2026 19:29:08 +0800 Subject: [PATCH] change avatar (and other images) to relative path of s3 bucket --- app/auth.py | 5 +++-- app/utils/format.py | 12 ++++++++++++ app/utils/s3.py | 13 ++++++------- 3 files changed, 21 insertions(+), 9 deletions(-) create mode 100644 app/utils/format.py diff --git a/app/auth.py b/app/auth.py index 1db32d9..c9dc294 100644 --- a/app/auth.py +++ b/app/auth.py @@ -7,6 +7,7 @@ from app.auth.deps import get_current_user from app.db import SessionLocal from app.models import User from app.auth.jwt import create_jwt_token, create_refresh_token, decode_token +from app.utils.format import get_image_url router = APIRouter() @@ -114,7 +115,7 @@ async def auth_callback(request: Request, code: str, state: str): "user": { "email": user.email, "name": user.name, - "avatar": user.avatar, + "avatar": get_image_url(user.avatar), } } @@ -123,7 +124,7 @@ def me(user = Depends(get_current_user)): return { "email": user.email, "name": user.name, - "avatar": user.avatar, + "avatar": get_image_url(user.avatar), } @router.post("/refresh") diff --git a/app/utils/format.py b/app/utils/format.py new file mode 100644 index 0000000..d4f20bf --- /dev/null +++ b/app/utils/format.py @@ -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}" \ No newline at end of file diff --git a/app/utils/s3.py b/app/utils/s3.py index e089ca9..29637c2 100644 --- a/app/utils/s3.py +++ b/app/utils/s3.py @@ -38,13 +38,12 @@ async def upload_google_avatar_to_s3(google_avatar_url: str, user_id: str) -> st # 在高并发下建议使用 run_in_executor,初期可以直接这样写 bucket.put_object(object_name, image_data, headers=headers) - # 4. 生成公开访问的 URL - # 阿里云 OSS 标准 URL 格式: https://bucket-name.endpoint/object-name - # 例如: https://character-roleplay-dev-asset.oss-ap-northeast-1.aliyuncs.com/avatars/xxx/avatar.jpg - host = ENDPOINT.replace("https://", "") - oss_url = f"https://{BUCKET_NAME}.{host}/{object_name}" - - return oss_url + # 不直接返回公开访问的 URL,而是返回 OSS 内部相对路径,前端可以通过 CDN 或后端代理访问 + # 这样可以支持后续更换存储服务,以及更换 OSS_BASE_URL 域名而不影响前端 + # host = ENDPOINT.replace("https://", "") + # oss_url = f"https://{BUCKET_NAME}.{host}/{object_name}" + # return oss_url + return object_name except Exception as e: # 打印错误日志,生产环境建议使用 logger