添加图片下载能力
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""图片下载工具。
|
||||
|
||||
把图片 URL 下载成字节流,供 OCR(app.tool.ocr)与二维码识别
|
||||
(app.tool.cv / app.tool.qr_decode)直接消费,不落盘。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
|
||||
from app.core.logger import log
|
||||
|
||||
# 请求超时(秒)
|
||||
_TIMEOUT = 20
|
||||
|
||||
|
||||
def download_image(url: str) -> bytes | None:
|
||||
"""下载图片。
|
||||
|
||||
Args:
|
||||
url: 图片地址。
|
||||
|
||||
Returns:
|
||||
图片字节流;下载失败时返回 None。
|
||||
"""
|
||||
if not url or not url.startswith("http"):
|
||||
return None
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=_TIMEOUT, follow_redirects=True) as client:
|
||||
response = client.get(url)
|
||||
response.raise_for_status()
|
||||
return response.content or None
|
||||
except httpx.HTTPError as exc:
|
||||
log.warning(f"图片下载失败: {url} | {exc}")
|
||||
return None
|
||||
Reference in New Issue
Block a user