35 lines
1 KiB
Python
35 lines
1 KiB
Python
# anime_etl/images/downloader.py
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from typing import Final
|
||
|
||
import httpx
|
||
|
||
IMAGE_SERVICE_URL: Final[str] = os.getenv(
|
||
"NYANIMEDB_IMAGE_SERVICE_URL",
|
||
"http://127.0.0.1:8000"
|
||
)
|
||
|
||
|
||
async def ensure_image_downloaded(url: str, subdir: str = "posters") -> str:
|
||
"""
|
||
Просит image-service скачать картинку по URL и сохранить её у себя.
|
||
|
||
Возвращает относительный путь (subdir/ab/cd/<sha1>.ext),
|
||
который можно писать в images.image_path.
|
||
"""
|
||
async with httpx.AsyncClient(timeout=20.0) as client:
|
||
resp = await client.post(
|
||
f"{IMAGE_SERVICE_URL}/download-by-url",
|
||
json={"url": url, "subdir": subdir},
|
||
)
|
||
resp.raise_for_status()
|
||
data = resp.json()
|
||
|
||
# ожидаем {"path": "..."}
|
||
path = data["path"]
|
||
if not isinstance(path, str):
|
||
raise RuntimeError(f"Invalid response from image service: {data!r}")
|
||
|
||
return path
|