fix(aiot): COS 未启用时 get_url 返回空字符串而非裸 object_key
修复告警截图显示为损坏图片的根因: - get_url() 保证返回值为 http(s) URL 或空字符串 - _init() 捕获 COS 初始化异常,优雅降级而非崩溃 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -175,9 +175,13 @@ class COSStorage:
|
||||
logger.info("COS 未启用 (COS_ENABLED=false)")
|
||||
return
|
||||
|
||||
self._client = _get_cos_client()
|
||||
if self._client:
|
||||
self._enabled = True
|
||||
try:
|
||||
self._client = _get_cos_client()
|
||||
if self._client:
|
||||
self._enabled = True
|
||||
except Exception as e:
|
||||
logger.error(f"COS 初始化失败,截图预签名 URL 将不可用: {e}")
|
||||
self._enabled = False
|
||||
|
||||
@property
|
||||
def is_cos_mode(self) -> bool:
|
||||
@@ -278,12 +282,21 @@ class COSStorage:
|
||||
# ======================== 兼容旧接口 ========================
|
||||
|
||||
def get_url(self, path: str) -> str:
|
||||
"""获取访问 URL(兼容旧代码调用)"""
|
||||
"""获取访问 URL(兼容旧代码调用)
|
||||
|
||||
保证返回值要么是 http(s):// 开头的可访问 URL,要么是空字符串。
|
||||
绝不返回裸 object_key,以免前端加载为相对路径导致损坏图片。
|
||||
"""
|
||||
if not path:
|
||||
return ""
|
||||
if path.startswith("http"):
|
||||
return path
|
||||
return self.get_presigned_url(path)
|
||||
url = self.get_presigned_url(path)
|
||||
# 兜底:如果未能生成有效 URL(COS 未启用/异常),返回空字符串
|
||||
if not url.startswith("http"):
|
||||
logger.warning(f"无法生成 COS 预签名 URL,返回空: object_key={path}")
|
||||
return ""
|
||||
return url
|
||||
|
||||
|
||||
# 全局单例
|
||||
|
||||
Reference in New Issue
Block a user