change avatar (and other images) to relative path of s3 bucket
This commit is contained in:
@@ -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
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user