Flask-流式传输内容保持上下文

Flask - Stream content keeping context

本文关键字:上下文 传输 Flask-      更新时间:2023-09-26

我正在使用以下Flask代码来流式传输命令的输出:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        ...
        # some logic to get cmd from POST request
        ...
        return redirect_to(url_to(stream, cmd=cmd))
    return render_template('index.html')
@app.route('/stream/<cmd>')
def stream(cmd):
    print("Executing %s" % cmd)
    g = proc.Group()
    p = g.run(cmd)
    def stream_cmd():
        while g.is_pending():
            lines = g.readlines()
            for proc, line in lines:
                print(line)
                yield line + '</br>'
    return Response(stream_cmd(), mimetype='text/html')  # text/html is required for most browsers to show th$

当我发布表单时,它会重定向到一个空白页面,在那里我可以看到流的输出,但我失去了所有的布局/css/html/etc。。。

如何在看到流输出的同时保持当前布局

理想情况下,我希望能够使用流输出(Jquery)动态更新当前页面中的<div>元素(而不是重定向),但我不确定这是否可能。

根据@reptilicus的建议,我重写了代码以使用websocket。

这是工作代码:

Python

@socketio.on('message', namespace='/stream')
def stream(cmd):
    # Streams output of a command
    from shelljob import proc
    g = proc.Group()
    p = g.run(cmd)
    while g.is_pending():
        lines = g.readlines()
        for proc, line in lines:
            send(line, namespace='/stream')
            eventlet.sleep(0) # THIS IS MANDATORY

接收send调用发送的消息的相应JavaScript如下:

JavaScript(JQuery)

var socket = io.connect('http://' + document.domain + ':' + location.port + '/stream')
socket.on('message', function(msg){
  $('#streaming_text').append(msg);
})
...
jqxhr.done(function(cmd){ # This is executed after an AJAX post, but you can change this to whatever event you like
  socket.send(cmd)
  return false; 
})