Flask创建流式返回的mock脚本

需求:对接口api/mocktest 接口进行流式返回的mock,其中要求接口请求方式为:api/mocktest/{first_time}/{total_time},first_time为首token耗时、total_time为流式返回总耗时

python 复制代码
import sys
from flask import Flask, Response, request
import json
import time

app = Flask(__name__)

@app.route("/api/mocktest/<int:first_time>/<int:total_time>", methods=["POST"])
def process(first_time, total_time):
    if first_time >= total_time:
        return Response(json.dumps({"error": "First time is greater than total time"}), status=400)

    """
    /api接口定义,动态获取first token time和complete response time
    """
    stream = request.json.get("stream")
    stream_num = 10
    # 根据请求参数计算平均时间
    avg_time = (total_time - first_time) / (stream_num - 1)
    # 初始化流式数据
    mock_stream_data = [[json.dumps({"data": "this is a stream mock1", "status": 0}), first_time]]
    for i in range(2, stream_num + 1):
        res = [json.dumps({"data": "this is a stream mock" + str(i), "status": 0}), avg_time]
        mock_stream_data.append(res)

    # 初始化非流式数据
    no_stream_time = first_time
    mock_nostream_data = [
        [json.dumps({"data": "this is a nostream mock", "status": 0}), no_stream_time]
    ]

    def generate_stream():
        """
        流式返回数据
        """
        for each in mock_stream_data:
            v = each[0]
            t = each[1]
            if t > 0:
                time.sleep(t)  # 等待指定的时间后再发送下一条数据
            yield v + "\r\n"
            sys.stdout.flush()

    def generate_nostream():
        """
        非流式返回数据
        """
        v = mock_nostream_data[0][0]
        t = mock_nostream_data[0][1]
        if t > 0:
            time.sleep(t)
        yield v + "\r\n"

    if stream:
        return Response(generate_stream(), mimetype="text/plain")
    else:
        return Response(generate_nostream(), mimetype="text/plain")

app.run()

python运行后通过curl命令访问地址:

流式请求:

bash 复制代码
curl --location '127.0.0.1:5000/api/mocktest/3/10' \
--header 'Content-Type: application/json' \
--data '{
    "messages": [{"role": "user", "content": "发起请求"}],
    "stream": true
}'

结果:

非流式请求:

bash 复制代码
curl --location '127.0.0.1:5000/api/mocktest/3/10' \
--header 'Content-Type: application/json' \
--data '{
    "messages": [{"role": "user", "content": "发起请求"}],
    "stream": false
}'

结果:

相关推荐
就叫你天选之人啦4 分钟前
安装torch+vllm+flash_attn的prompt
人工智能·pytorch·python
aramae7 分钟前
模拟实现memset()(C语言)
c语言·开发语言·后端
2501_9339232527 分钟前
Spring Bean作用域揭秘:单例、原型、请求与会话的区别
java·后端·spring·java-ee
wuyk55537 分钟前
21.计数排序:不用比较的“空间换时间”排序算法
python·算法·排序算法
智码看视界38 分钟前
第4篇:循环神经网络及其变体 LSTM/GRU 实战
python·自然语言处理·gru·lstm·循环神经网络·情感分析·梯度消失
Web3&Basketball39 分钟前
Agent外传审计实战:3类失准事故拦截脚本
python·大模型·agent·性能调优·推理优化
何以解忧,唯有..1 小时前
Milvus 向量数据库的 DDL、DML、DQL 操作详解
python
罗狮粉 991 小时前
AI-Gateway — 面向 AI Agent 的本地 Runtime Gateway
人工智能·python·inscode·ai编程
蓝胖的四次元口袋1 小时前
Python数据结构知识梳理
python
程序员清风1 小时前
生产级智能体平台设计:任务编排、工具管理与运行监控
人工智能·python·aigc