0


flask :stream_with_context流内容 + 前端请求

python flask 使用 stream_with_context

通过yield 流式返回 数据

from flask import  stream_with_context, Response
from time import sleep

progress_bar_ratio = 0.

def get_bar_ratio():
    global progress_bar_ratio
    progress_bar_ratio += 1
    return progress_bar_ratio

@app.route('/api/stream')
def progress():

    @stream_with_context
    def generate():
        # global ratio
        # ratio = get_bar_ratio()  #获取后端进度条数据,最初的时候是0
        for ratio in range(10):

        # while ratio < 10:  #循环获取,直到达到100%
            yield "data:" + str(ratio) + "\n\n"
            print("ratio:", ratio)
            #最好设置睡眠时间,不然后端在处理一帧的过程中前端就访问了好多次
            sleep(1)
    return Response(generate(), mimetype='text/event-stream')

前端请求示例

var source: any = new EventSource("/api/stream", { withCredentials: true })
    source.onmessage = function (event) {
      console.log(event.data)
      if (event.data >= 9) {
        source.close()
      }
    }

@microsoft/fetch-event-source 可配置请求method 、headers、请求参数等。

import { fetchEventSource } from '@microsoft/fetch-event-source'

        this.ctrl = new AbortController()
        console.log(this.ctrl)
        this.eventSource = fetchEventSource('/runmonitor/operationtool/execute', {
            method: 'POST',
            signal: that.ctrl.signal,
            headers: {
                "Content-Type": 'application/json',
            },
            body: JSON.stringify(that.executeform),
            onmessage(event) {
                    if (event.data == 'done') {
                        //ctrl.abort 停止eventsource
                        that.ctrl.abort()
                        that.eventSource = null
                    }
                    else {
                        that.data.push(event.data)
                       
                    }
                
            },
            async onopen(response) {
                // 开始
                console.log(response)
            },
            onerror(event) {
                that.ctrl.abort()
                that.eventSource = null
                // throw new Error 结束eventSource 
                throw new Error(event)
            }
        })

EventSource.close() 关闭连接

结束后 需要使用 close() 关闭连接 否则会重复请求

一个接口内,结果流式返回

EventSource.onopen 是一个事件处理器,它在收到

open

事件时被调用,在那时,连接刚被打开。

EventSource.onmessage 会在通过事件源收到数据时触发。

EventSource.onerror 是当发生错误且这个错误事件(error)被 EventSource 触发时调用的一个事件处理函数。

标签: flask 前端 python

本文转载自: https://blog.csdn.net/asdq2w3d/article/details/131432889
版权归原作者 、好多鱼 所有, 如有侵权,请联系我们删除。

“flask :stream_with_context流内容 + 前端请求”的评论:

还没有评论