Files
PTGen/pt_gen/services/uploader.py
DengDai 644b5aaaf8 init
2025-12-08 14:47:24 +08:00

35 lines
1.4 KiB
Python
Raw Permalink 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.
import httpx
from . import uploader
class ImageUploader:
def __init__(self, api_url: str, api_key: str):
self.api_url = api_url
self.api_key = api_key
async def upload(self, image_url: str) -> str:
"""
从一个URL下载图片然后上传到你自己的图床。
你需要根据你的图床 API 修改这部分代码。
"""
try:
async with httpx.AsyncClient() as client:
# 1. 下载图片
get_resp = await client.get(image_url)
get_resp.raise_for_status()
image_bytes = get_resp.content
# 2. 上传到你的图床
# 这是一个通用示例,你需要修改 files 和 headers
files = {'file': ('poster.jpg', image_bytes, 'image/jpeg')}
headers = {'Authorization': f'Bearer {self.api_key}'}
post_resp = await client.post(self.api_url, files=files, headers=headers)
post_resp.raise_for_status()
# 3. 解析响应返回新的图片URL
# 假设返回的JSON是 {"data": {"url": "..."}}
return post_resp.json()['data']['url']
except Exception as e:
print(f"图片上传失败: {e}")
return image_url # 上传失败返回原始URL