Qwen-Image-2512-ComfyUI代码实例:Python调用API指南
1. 引言:为什么你需要用Python调用Qwen-Image-2512-ComfyUI
你是不是已经成功部署了 Qwen-Image-2512-ComfyUI 镜像,并通过网页界面生成了几张惊艳的图片?但如果你还停留在“点一点出图”的阶段,那可就浪费了它真正的潜力。
自动化、批量生成、集成到项目中——这些才是高效使用AI图像模型的关键。而实现这一切的核心方式,就是通过Python 调用 ComfyUI 的 API。
本文将手把手带你从零开始,理解 ComfyUI 的 API 工作机制,并提供可直接运行的 Python 代码示例,让你不仅能手动出图,还能让程序自动帮你生成成百上千张符合需求的图像。
无论你是想搭建一个自动海报生成系统,还是为内部工具添加AI绘图能力,这篇指南都能让你快速上手。
2. 环境准备与基础确认
在写代码之前,我们必须确保环境已经正确运行,并且 API 功能已启用。
2.1 确认你的镜像已正常运行
根据你提供的快速启动流程,请先完成以下步骤:
- 在算力平台部署
Qwen-Image-2512-ComfyUI镜像(支持 4090D 单卡) - 进入
/root目录,运行1键启动.sh脚本 - 启动成功后,点击“返回我的算力”,打开 ComfyUI 网页端
当你能在浏览器中看到 ComfyUI 的可视化工作流界面时,说明服务已经就绪。
2.2 检查API是否可用
ComfyUI 默认启用了 RESTful API 接口,我们可以通过访问以下地址来确认:
http://你的服务器IP:7860/如果页面正常加载,说明 Web UI 和 API 服务都在运行。
更进一步,你可以访问:
http://你的服务器IP:7860/api/v1/prompt这会返回当前队列中的提示信息(初始为空),证明 API 可用。
重要提示:请确保你的服务器防火墙或安全组规则允许外部访问 7860 端口(或你自定义的端口),否则本地脚本无法连接。
3. 理解ComfyUI的API工作机制
要通过 Python 控制 ComfyUI,我们必须了解它的“大脑”是怎么工作的。
3.1 工作流(Workflow)的本质是JSON
你在 ComfyUI 界面上拖拽节点、连线构成的工作流,其实背后是一个结构化的 JSON 数据。当你点击“运行”时,这个 JSON 就会被发送给后端执行。
所以,Python 调用 API 的本质,就是构造正确的 JSON 请求,发送给 ComfyUI 的 API 端点。
3.2 关键API接口说明
| 接口 | 方法 | 作用 |
|---|---|---|
/prompt | POST | 提交一个新的生成任务 |
/history | GET | 获取历史生成记录 |
/queue | GET | 查看当前队列状态 |
/ws | WebSocket | 实时接收生成进度和结果 |
我们将重点使用/prompt接口来提交任务。
4. 获取你的工作流JSON数据
既然 API 需要 JSON,那我们怎么拿到它?
4.1 从内置工作流导出
- 打开 ComfyUI 网页端
- 点击左侧“内置工作流”
- 选择一个适合 Qwen-Image-2512 的工作流(通常包含文本编码、采样器、VAE 解码等节点)
- 点击右上角菜单 → “Save (Prompt)” 保存为
.json文件
或者,你也可以直接复制画布上的工作流内容到剪贴板。
4.2 示例工作流结构(简化版)
{ "3": { "inputs": { "text": "a beautiful sunset over the mountains", "clip": ["10", 1] }, "class_type": "CLIPTextEncode" }, "10": { "inputs": { "model": ["4", 0], "clip": ["5", 0] }, "class_type": "CLIPSetLastLayer" }, "4": { "inputs": { "ckpt_name": "qwen_image_2512.safetensors" }, "class_type": "CheckpointLoaderSimple" }, ... }这个 JSON 描述了整个图像生成流程:加载模型、处理提示词、执行采样、输出图像。
5. Python调用API完整代码示例
现在进入正题——如何用 Python 发送请求。
5.1 安装依赖
pip install requests websockets5.2 基础提交任务代码
import requests import uuid # 配置服务器地址 SERVER_ADDRESS = "http://你的IP:7860" # 加载你导出的工作流JSON with open("qwen_workflow.json", "r") as f: prompt_data = json.load(f) def queue_prompt(prompt): """提交生成任务""" p = {"prompt": prompt} resp = requests.post(f"{SERVER_ADDRESS}/api/v1/prompt", json=p) return resp.json() # 提交任务 result = queue_prompt(prompt_data) print("任务已提交,响应:", result)运行这段代码后,你会在 ComfyUI 界面看到新的生成任务正在执行。
5.3 获取生成结果
任务提交后,我们需要获取生成的图片。可以通过/history接口查询。
import time import json def get_history(prompt_id): """根据任务ID获取历史记录""" url = f"{SERVER_ADDRESS}/api/v1/history/{prompt_id}" while True: resp = requests.get(url) if resp.status_code == 200: history = resp.json() if prompt_id in history and history[prompt_id].get("outputs"): return history[prompt_id] time.sleep(1) # 每秒检查一次 # 使用示例 prompt_id = result['prompt_id'] print(f"等待任务 {prompt_id} 完成...") final_output = get_history(prompt_id) print("生成完成,输出信息:", final_output)5.4 完整自动化脚本(推荐使用)
import requests import json import time import uuid class ComfyUIClient: def __init__(self, server_address="http://localhost:7860"): self.server_address = server_address def load_workflow(self, file_path): with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) def update_prompt_text(self, workflow, new_text): """更新提示词节点""" for node in workflow.values(): if node.get("class_type") == "CLIPTextEncode": if "text" in node["inputs"]: node["inputs"]["text"] = new_text return workflow def queue_prompt(self, prompt): resp = requests.post(f"{self.server_address}/api/v1/prompt", json={"prompt": prompt}) return resp.json() def get_history(self, prompt_id): while True: resp = requests.get(f"{self.server_address}/api/v1/history/{prompt_id}") if resp.status_code == 200: history = resp.json() if prompt_id in history and history[prompt_id].get("outputs"): return history[prompt_id] time.sleep(1) def generate_image(self, workflow_file, prompt_text): workflow = self.load_workflow(workflow_file) workflow = self.update_prompt_text(workflow, prompt_text) result = self.queue_prompt(workflow) prompt_id = result['prompt_id'] print(f"✅ 任务 {prompt_id} 已提交") output = self.get_history(prompt_id) # 提取图片路径或URL for node_id, node_output in output["outputs"].items(): if "images" in node_output: for img in node_output["images"]: print(f"🎨 图片已生成: {img['filename']} (保存在 {img['subfolder']})") return img return None # 使用示例 client = ComfyUIClient("http://你的服务器IP:7860") image_info = client.generate_image( workflow_file="qwen_workflow.json", prompt_text="a futuristic city at night, neon lights, raining, cinematic" )6. 实用技巧与常见问题
6.1 如何批量生成不同图片?
只需在一个循环中调用generate_image方法即可:
prompts = [ "a red apple on a wooden table", "a blue car driving on highway", "a cat sitting on window sill" ] for prompt in prompts: client.generate_image("qwen_workflow.json", prompt) time.sleep(2)6.2 如何修改图像尺寸?
在工作流 JSON 中找到采样器节点(如KSampler),修改其width和height参数:
"6": { "inputs": { "width": 1024, "height": 1024, "batch_size": 1 }, "class_type": "EmptyLatentImage" }你可以在 Python 中动态修改这些值:
def set_resolution(workflow, width, height): for node in workflow.values(): if node.get("class_type") == "EmptyLatentImage": node["inputs"]["width"] = width node["inputs"]["height"] = height return workflow6.3 常见问题排查
| 问题 | 可能原因 | 解决方法 |
|---|---|---|
| 连接被拒绝 | IP或端口错误、防火墙阻挡 | 检查服务器IP和端口,开放7860端口 |
| 提示词不生效 | 节点ID错误或未正确更新 | 确认CLIPTextEncode节点ID,打印JSON验证 |
| 模型未加载 | ckpt_name不匹配 | 检查CheckpointLoaderSimple中的模型文件名 |
| 无返回结果 | 任务卡住或超时 | 查看ComfyUI日志,确认GPU资源充足 |
7. 总结:从手动操作到程序化控制
通过本文的实践,你应该已经掌握了如何:
- 理解 ComfyUI 的 API 工作机制
- 导出并修改工作流 JSON
- 使用 Python 自动提交生成任务
- 获取生成结果并集成到自己的项目中
这不仅仅是“调个接口”那么简单,而是将 AI 图像生成能力真正变成你应用的一部分。无论是做内容批量生产、设计辅助工具,还是构建AI产品原型,这套方法都能大幅提升效率。
下一步,你可以尝试:
- 将生成结果自动上传到云存储
- 添加图像质量过滤机制
- 构建Web前端让用户输入提示词
- 结合数据库记录每次生成的历史
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。