uniapp stream流式请求怎么实现

后端接口是基于stream的接口,前端用的是uniapp生成的微信小程序应用,怎么在小程序中请求并达到流式请求内容。
目前使用python flask 做的服务端测试,但是前端没找到合适的方式
python 服务端代码如下 :

from flask import Flask, Response
import time

app = Flask(__name__)
@app.route('/stream')
def stream():
    def generate():
        for i in range(10):
            yield str(i)
            time.sleep(1)
    return Response(generate(), mimetype='text/plain')

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')

好用的python模拟客户端代码如下:

import requests

import time 

response = requests.get('http://127.0.0.1:5000/stream', stream=True)

for chunk in response.iter_content():
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),chunk)

目前服务端做的每秒循环输出一个数字内容,python模拟客户端也是一次请求,然后每秒进行接收一次数据,但是在前端小程序中,怎么才能达到这个效果。

你可以用gpt回答,但是请先自己跑一下代码再来回答,如果代码没有undefined再发上来


Page({
  data: {
    streamData: '',
  },

  onLoad: function () {
    wx.request({
      url: 'http://127.0.0.1:5000/stream',
      stream: true,
      success: (res) => {
        res.onData((chunk) => {
          this.setData({
            streamData: this.data.streamData + chunk,
          });
        });

        res.onEnd(() => {
          console.log('stream end');
        });
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
})

用websocket吧

参考GPT和自己的思路:在前端uni-app中,可以使用uni.request来实现流式请求。需要注意的是,要在请求header中加上{'content-type': 'application/octet-stream'},指定请求内容类型为二进制流,然后在success回调函数中逐步获取数据。

下面是一个示例代码:

uni.request({
  url: 'http://127.0.0.1:5000/stream',
  method: 'GET',
  responseType: 'arraybuffer',
  header: {
    'content-type': 'application/octet-stream'
  },
  success: function(res) {
    // 通过 TextDecoder 将二进制数据转换为字符串
    const decoder = new TextDecoder('utf-8');
    const stream = res.data;
    let buf = new Uint8Array(1024);
    let offset = 0;

    const intervalId = setInterval(() => {
      const chunk = stream.slice(offset, offset + 1024);
      buf.set(new Uint8Array(chunk), 0);
      offset += chunk.byteLength;

      const result = decoder.decode(buf.slice(0, chunk.byteLength));
      console.log(result);

      if (offset >= stream.byteLength) {
        clearInterval(intervalId);
      }
    }, 1000);
  }
});


上面的代码中,使用uni.request发起GET请求,指定响应类型为二进制数组,然后在success回调函数中逐步获取数据。在回调函数中,创建一个TextDecoder实例,用来将二进制数据转换为字符串。然后创建一个Uint8Array类型的缓冲区buf,每隔1秒钟读取1024字节的数据,将其存入缓冲区,然后将缓冲区的内容转换为字符串,并打印出来。当读取完全部数据时,清除定时器。

以下答案由GPT-3.5大模型与博主波罗歌共同编写:
根据你提供的Python后端代码,服务器端的流式传输已经实现了。因此,你只需要在前端发起基于stream的请求并接收响应即可。

Uniapp中你可以使用小程序API wx.request() 来完成请求,此函数允许通过传入一个options对象来发送请求。为了实现流式传输,我们需要在options中指定特定的headers和responseType,在发出请求时设置options的属性。 具体实现如下:

```
wx.request({
url: 'http://0.0.0.1/