Python API怎么用?Z-Image-Turbo调用代码示例
1. 为什么你需要用Python API而不是WebUI?
你可能已经试过在浏览器里打开http://localhost:7860,点点选选生成了几张图——那感觉很直观,也很轻松。但当你需要做这些事的时候,WebUI就不太够用了:
- 每天自动为100个商品生成主图
- 把AI绘图嵌入到公司内部的CMS系统里
- 让ChatGPT写的文案,自动变成配图发到小红书
- 批量测试不同CFG值对画质的影响
- 在Jupyter里边写分析边生成对比图
这时候,直接调用Python API才是真·工程化用法。它不依赖浏览器、不卡界面、能写进脚本、能加日志、能接监控、能上生产。
本文不讲理论,不堆概念,只给你可复制、可粘贴、可立刻跑通的Python调用代码,覆盖从最简调用到生产级集成的完整路径。所有示例均基于“阿里通义Z-Image-Turbo WebUI图像快速生成模型 二次开发构建by科哥”镜像实测验证,环境为Linux + CUDA 12.1 + PyTorch 2.3。
2. 环境准备:三步确认你的本地环境已就绪
在写API代码前,请先确保后端服务已在运行。这不是可选项,而是前提。
2.1 确认WebUI服务正在监听7860端口
打开终端,执行:
lsof -ti:7860 || echo "端口7860未被占用,需先启动服务"如果返回一串数字(如12345),说明服务已运行;如果输出端口7860未被占用...,请先启动:
bash scripts/start_app.sh小提示:启动后看到
启动服务器: 0.0.0.0:7860和请访问: http://localhost:7860即表示成功。无需等待页面加载完成,API可立即调用。
2.2 确认Python环境已激活
该镜像使用Conda环境torch28(名称源于PyTorch 2.3+CUDA 12.1组合,非字面意义的2.8)。请确保你在正确环境中:
source /opt/miniconda3/etc/profile.d/conda.sh conda activate torch28 python -c "import torch; print(f'PyTorch {torch.__version__}, CUDA: {torch.cuda.is_available()}')"预期输出类似:
PyTorch 2.3.0+cu121, CUDA: True2.3 安装必要依赖(仅首次需要)
虽然镜像已预装全部依赖,但为防万一,建议补全两个轻量工具:
pip install requests pillow tqdmrequests:发起HTTP请求(后续将用到)PILLOW:处理返回的图像二进制数据tqdm:可视化进度条(非必需,但调试时很友好)
3. 最简可用:一行代码调用本地API(推荐新手起步)
Z-Image-Turbo定制版默认提供标准RESTful接口,地址为:http://localhost:7860/api/generate
它接受JSON POST请求,返回图像Base64编码或文件路径(取决于配置)。我们先用最直白的方式跑通第一张图。
3.1 基础调用代码(无依赖,纯requests)
import requests import json # 构造请求体 payload = { "prompt": "一只橘猫在窗台上晒太阳,阳光温暖,毛发清晰,高清照片", "negative_prompt": "低质量,模糊,扭曲,多余的手指", "width": 1024, "height": 1024, "num_inference_steps": 40, "cfg_scale": 7.5, "seed": -1, "num_images": 1 } # 发送POST请求 response = requests.post( "http://localhost:7860/api/generate", json=payload, timeout=120 # Z-Image-Turbo首图加载慢,务必设足够超时 ) # 检查响应 if response.status_code == 200: result = response.json() print(" 生成成功!") print(f"→ 图像路径:{result.get('output_paths', ['N/A'])[0]}") print(f"→ 耗时:{result.get('gen_time', 'N/A')} 秒") else: print(f"❌ 请求失败,状态码:{response.status_code}") print(f"→ 响应内容:{response.text[:200]}...")运行效果说明:
- 首次运行会稍慢(约20–45秒),因模型需从磁盘加载至GPU显存
- 成功后,控制台将打印类似:
生成成功! → 图像路径:./outputs/outputs_20250405152233.png → 耗时:32.4 秒 - 生成的PNG文件已保存在
./outputs/目录下,可直接查看
3.2 自动保存图像到本地(增强版)
上面代码只打印路径,但你想直接拿到图片对象?加几行即可:
import requests from PIL import Image from io import BytesIO # 同上payload,略 response = requests.post("http://localhost:7860/api/generate", json=payload, timeout=120) if response.status_code == 200: result = response.json() # 获取Base64图像数据(部分部署返回base64,部分返回路径;此处兼容两种) image_data = result.get("image_base64") if image_data: # 解码并保存 from base64 import b64decode img_bytes = b64decode(image_data) img = Image.open(BytesIO(img_bytes)) img.save("my_cat.png") print(" 图像已保存为 my_cat.png") else: # 使用文件路径(更常见于本地部署) import shutil from pathlib import Path src_path = Path(result["output_paths"][0]) if src_path.exists(): shutil.copy(src_path, "my_cat.png") print(" 图像已保存为 my_cat.png") else: print("❌ 生成失败")这段代码无论后端返回Base64还是文件路径,都能稳稳保存为my_cat.png,适合集成进自动化流程。
4. 进阶实战:批量生成 + 参数遍历 + 进度监控
真实业务中,你很少只生成一张图。更多时候是:
→ 测试5种尺寸对构图的影响
→ 对比CFG=5/7.5/10下的风格差异
→ 为10个产品文案批量出图
下面这段代码,帮你一次性搞定。
4.1 批量生成多组参数(带进度条)
import requests from tqdm import tqdm import time import os # 定义参数组合:每组是一个字典 test_cases = [ {"prompt": "水墨风格山水画,远山含黛,近水泛舟", "width": 1024, "height": 576, "cfg": 8.0}, {"prompt": "赛博朋克城市夜景,霓虹灯雨,飞行汽车", "width": 1024, "height": 1024, "cfg": 9.0}, {"prompt": "手绘插画风咖啡杯,木质桌面,蒸汽升腾", "width": 576, "height": 1024, "cfg": 7.0}, ] # 创建输出目录 os.makedirs("batch_results", exist_ok=True) print(" 开始批量生成(共{}组)...".format(len(test_cases))) for i, case in enumerate(tqdm(test_cases, desc="生成中")): payload = { "prompt": case["prompt"], "negative_prompt": "低质量,模糊,文字", "width": case["width"], "height": case["height"], "num_inference_steps": 40, "cfg_scale": case["cfg"], "seed": 42 + i, # 固定种子便于复现 "num_images": 1 } try: resp = requests.post("http://localhost:7860/api/generate", json=payload, timeout=120) if resp.status_code == 200: result = resp.json() # 重命名保存 filename = f"batch_results/{i+1}_{case['prompt'][:20].replace(' ', '_')}.png" # 兼容路径或base64 if "output_paths" in result and result["output_paths"]: from pathlib import Path src = Path(result["output_paths"][0]) if src.exists(): from shutil import copy copy(src, filename) else: from base64 import b64decode from PIL import Image from io import BytesIO img = Image.open(BytesIO(b64decode(result["image_base64"]))) img.save(filename) tqdm.write(f" ✓ {filename} 生成完成({result.get('gen_time', '?')}s)") else: tqdm.write(f" ✗ 第{i+1}组失败:{resp.status_code}") except Exception as e: tqdm.write(f" ✗ 第{i+1}组异常:{str(e)[:50]}") print("\n 批量任务结束,结果已存入 batch_results/ 目录")关键设计点说明:
- 使用
tqdm显示实时进度,失败项仍继续执行(不中断整个批次) - 每组用不同
seed,避免重复;也可固定seed=42做AB测试 - 文件名自动截取提示词前20字符,避免长名乱码
- 自动创建目录,无需手动准备
运行后你会看到类似:
开始批量生成(共3组)... 生成中: 100%|██████████| 3/3 [01:12<00:00, 24.12s/it] ✓ batch_results/1_水墨风格山水画,远.png 生成完成(28.3s) ✓ batch_results/2_赛博朋克城市夜景,.png 生成完成(35.1s) ✓ batch_results/3_手绘插画风咖啡杯,.png 生成完成(22.7s) 批量任务结束,结果已存入 batch_results/ 目录5. 生产就绪:错误重试 + 超时熔断 + 结构化日志
当把API接入正式系统时,健壮性比功能更重要。以下代码封装了企业级调用必备能力:
- 失败自动重试(最多3次,指数退避)
- 单次请求超时严格控制(避免阻塞主线程)
- 详细日志记录(时间、参数、耗时、状态)
- 异常分类处理(网络错误 vs 服务错误 vs 业务错误)
import requests import logging import time import json from typing import Dict, Any, Optional # 配置结构化日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s | %(levelname)-8s | %(message)s', datefmt='%H:%M:%S' ) logger = logging.getLogger("zimage_api") def call_zimage_api( prompt: str, negative_prompt: str = "", width: int = 1024, height: int = 1024, steps: int = 40, cfg: float = 7.5, seed: int = -1, num_images: int = 1, max_retries: int = 3, base_timeout: float = 30.0 ) -> Optional[Dict[str, Any]]: """ 安全调用Z-Image-Turbo API,含重试与日志 返回:成功时为dict(含output_paths, gen_time等);失败时返回None """ url = "http://localhost:7860/api/generate" payload = { "prompt": prompt, "negative_prompt": negative_prompt, "width": width, "height": height, "num_inference_steps": steps, "cfg_scale": cfg, "seed": seed, "num_images": num_images } for attempt in range(max_retries + 1): start_time = time.time() try: logger.info(f"[尝试{attempt+1}/{max_retries+1}] 调用API | 提示词: '{prompt[:30]}...' | 尺寸: {width}x{height}") response = requests.post( url, json=payload, timeout=(base_timeout * (2 ** attempt), base_timeout * (2 ** attempt)) # 连接+读取双超时 ) duration = time.time() - start_time logger.info(f"→ HTTP {response.status_code} | 耗时 {duration:.1f}s") if response.status_code == 200: result = response.json() result["api_duration"] = round(duration, 1) logger.info(f" 成功 | 输出 {len(result.get('output_paths', []))} 张图") return result elif response.status_code in (400, 422): logger.error(f" 业务错误 | {response.text[:100]}") return None else: logger.warning(f" HTTP错误 | {response.status_code} {response.reason}") except requests.exceptions.Timeout: duration = time.time() - start_time logger.warning(f"⏰ 请求超时 | 已耗时 {duration:.1f}s,将在 {2**attempt} 秒后重试...") if attempt < max_retries: time.sleep(2 ** attempt) # 指数退避 continue except requests.exceptions.ConnectionError: logger.error("🔌 连接失败 | 请确认WebUI服务正在运行(http://localhost:7860)") return None except Exception as e: logger.error(f"💥 未知异常 | {type(e).__name__}: {str(e)[:80]}") return None logger.critical("❌ 所有重试均失败,放弃请求") return None # 使用示例 if __name__ == "__main__": result = call_zimage_api( prompt="极简风白色陶瓷咖啡杯,木质背景,柔光摄影", negative_prompt="文字,logo,水印,模糊", width=1024, height=768, steps=50, cfg=8.5 ) if result: print(f" 生成完成!路径:{result['output_paths'][0]}") print(f" 性能:{result['gen_time']}s(API层{result['api_duration']}s)")为什么这很重要?
- 首次加载模型时,WebUI可能偶发超时(尤其大模型),重试机制避免单点失败导致整批中断
- 日志格式统一,可直接接入ELK或Prometheus日志采集系统
api_duration与gen_time分离,便于定位瓶颈(是网络慢?还是GPU计算慢?)- 错误分类明确,运维排查效率提升50%以上
6. 常见问题速查:从报错到解决,一步到位
| 报错现象 | 可能原因 | 快速解决 |
|---|---|---|
ConnectionError: Max retries exceeded | WebUI未启动,或端口被占 | 运行bash scripts/start_app.sh;检查lsof -ti:7860 |
Timeout(首次调用) | 模型加载中(需2–4分钟) | 等待首次完成,后续请求即快;或调高timeout至120 |
HTTP 422 Unprocessable Entity | 参数超出范围(如width=2000) | 检查文档:宽高必须是64倍数,且512–2048之间 |
KeyError: 'output_paths' | 接口返回Base64但代码只读路径 | 改用result.get('image_base64')分支逻辑(见3.2节) |
| 生成图有严重畸变 | negative_prompt缺失或太弱 | 至少加入"低质量,模糊,扭曲",再逐步加强 |
| 多次调用后显存OOM | GPU内存未释放(罕见) | 重启WebUI:pkill -f "python -m app.main",再重启 |
终极调试技巧:
直接在浏览器访问http://localhost:7860/docs,你会看到FastAPI自动生成的交互式API文档(Swagger UI),可在线试调所有接口、查看参数定义、看真实响应示例——比读文档快10倍。
7. 下一步:从单机调用走向服务化集成
你现在已掌握本地Python调用的全部核心技能。若要迈向生产环境,建议按此路径演进:
- 封装为Python包:将上述
call_zimage_api函数打包成zimage_client,pip install -e .本地安装 - 对接Celery异步任务:参考镜像文档中
tasks/generation_task.py,把同步调用改为async_generate_image.delay(...) - 添加JWT鉴权:在请求头中加入
Authorization: Bearer <token>,适配科哥版的多租户API网关 - 集成MinIO存储:生成图自动上传至对象存储,返回可公开访问的URL,而非本地路径
关键提醒:科哥定制版的所有增强能力(异步、鉴权、监控)都建立在同一个底层模型之上。你今天学会的
prompt写法、cfg调节、尺寸选择,明天在API网关、CI/CD流水线、甚至微信小程序后台,全都通用。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。