nyanimedb/modules/anime_etl/images/downloader.py

35 lines
1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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