import time, random, httpx
def submit_with_retry(payload, max_attempts=5):
for attempt in range(max_attempts):
try:
r = httpx.post(f"{HOST}/v1/midjourney/generations/imagine",
json=payload,
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=30)
data = r.json()
if r.status_code == 200 and data["code"] in (1, 200):
return data
if data["code"] in (4, 24):
raise ValueError(data["description"]) # 不可重试
if data["code"] == 3 and "task" in data["description"]:
raise ValueError(data["description"]) # task_id 不存在
# 其余(9 / 429 / 5xx)可重试
except httpx.RequestError:
pass
time.sleep((4 ** attempt) + random.uniform(0, 1)) # 1s / 4s / 16s ...
raise RuntimeError(f"达到最大重试次数 {max_attempts}")