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
}'

结果:

相关推荐
q***721912 分钟前
Spring Boot环境配置
java·spring boot·后端
饮长安千年月15 分钟前
玄机-第八章 内存马分析-java03-fastjson
开发语言·python·安全·web安全·网络安全·应急响应
天天爱吃肉821820 分钟前
新能源汽车动力系统在环(HIL)半实物仿真测试台架深度解析
人工智能·python·嵌入式硬件·汽车
一 乐27 分钟前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小区互助系统
卡次卡次135 分钟前
注意点:挂载与插硬盘,容器挂载实现持久化存储
python
2401_8414956439 分钟前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
q***563839 分钟前
Spring Boot 集成 Kettle
java·spring boot·后端
MediaTea1 小时前
Python 第三方库:OpenPyXL(Excel 文件读写与操作)
开发语言·python·excel
会编程的吕洞宾1 小时前
Java Set集合:你的数据去重神器
java·后端·程序员
q***65691 小时前
Spring Data 什么是Spring Data 理解
java·后端·spring