我正在使用以下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 ......
如何在仍然看到流式输出的同时保持当前布局?
理想情况下,我希望能够动态地更新当前页面中的<div>
元素(而不是重定向),但是我不确定&# #39;甚至可能。
答案 0 :(得分:0)
按照@reptilicus推荐,我重写了代码以使用websockets。
以下是工作代码:
<强>的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;
})