gpt4 book ai didi

javascript - Flask - 流内容保持上下文

转载 作者:行者123 更新时间:2023-11-28 06:13:21 25 4
gpt4 key购买 nike

我正在使用以下 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/等...

如何在保持当前布局不变的同时仍能看到流式输出?

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

最佳答案

按照 @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;
})

关于javascript - Flask - 流内容保持上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com