flask流式接口

一、接口封装

复制代码
from flask import Flask, request, Response, stream_with_context
app = Flask(__name__)
app.logger.disabled = True

def chat_stream_(prompt):
    for new_text in ['1','2','3']:
        yield new_text

@app.route('/chat_stream', methods=['POST'])
def chat_stream():
    prompt = request.json['prompt']
    return app.response_class(stream_with_context(chat_stream_(prompt)))


if __name__ == '__main__':
    app.run('0.0.0.0', 1000)

二、接收流式返回

复制代码
import requests
url = "http://127.0.0.1:1000/chat_stream"
data = {"prompt":"怎么编研文档"}
res = requests.post(url, json=data, stream=True)
for token in res:
    print(token.decode("utf-8"))
相关推荐
天佑木枫18 分钟前
第2天:变量与数据类型 —— 让程序记住信息
python
阿正的梦工坊40 分钟前
【Rust】02-变量、不可变性与基础类型
开发语言·后端·rust
Dust-Chasing1 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
我叫黑大帅2 小时前
通过php 中的Route:: 的写法了解什么是静态类调用
后端·面试·php
Cloud_Shy6182 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
JS菌2 小时前
AI Agent 沙箱双层防护体系:从权限过滤到内核隔离的完整实现
前端·人工智能·后端
abcy0712133 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
IT空门:门主3 小时前
Spring 注入三剑客:@Resource、@Autowired、@RequiredArgsConstructor 到底该用哪个?
java·后端·spring
颜酱3 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
ServBay3 小时前
云端 AI 蜜月期宣告结束,为什么 2026 年开发者转向本地优先架构
后端·ai编程