如何通过网页关联Gradio接口?跨路径数据传递方案咨询
实现跨路径Gradio接口的数据传递
核心方案
通过FastAPI维护共享状态作为两个Gradio接口的数据中转,调整Gradio接口逻辑完成数据的读写操作。
完整代码实现
from fastapi import FastAPI import gradio as gr # 初始化FastAPI应用 app = FastAPI() # 共享状态:存储接口间传递的数据,小流量场景可用全局字典,多进程部署建议用Redis等分布式存储 shared_data = {"transcribed_result": ""} # 主接口(/路径)逻辑:处理输入并写入共享状态 def transcribe(text): # 替换为你的实际业务处理逻辑 processed_text = f"转换完成:{text}" shared_data["transcribed_result"] = processed_text return processed_text inp_interface = gr.Interface( fn=transcribe, inputs=gr.Textbox(label="输入需要转换的文本"), outputs=gr.Textbox(label="转换结果"), title="文本转换主接口" ) # 副接口(/other路径)逻辑:读取共享状态的数据 def fetch_result(): return shared_data.get("transcribed_result", "暂无转换数据") # 用Blocks构建副接口,添加刷新按钮主动获取最新数据 with gr.Blocks(title="结果接收接口") as out_interface: gr.Markdown("### 从主接口同步的转换结果") result_display = gr.Textbox(label="同步内容") gr.Button("刷新最新结果").click(fn=fetch_result, outputs=result_display) # 将两个Gradio应用挂载到FastAPI对应路径 app = gr.mount_gradio_app(app, inp_interface, path="/") app = gr.mount_gradio_app(app, out_interface, path="/other") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
关键说明
- 状态管理:全局字典
shared_data适用于单进程部署的小流量场景,若需多进程/多实例部署,需替换为Redis、Memcached等分布式存储方案。 - 接口逻辑调整:
- 主接口处理输入后直接将结果写入共享状态,无需额外输出配置。
- 副接口通过按钮触发读取操作,避免页面初始加载时无数据的问题。
- 自动同步优化:若需要实时自动同步,可在主接口处理完成后,通过前端JavaScript调用副接口的刷新逻辑,或使用FastAPI的WebSocket实现实时推送。
内容的提问来源于stack exchange,提问作者InsanityC.
相关产品推荐
相关产品推荐

