Javascript 在执行之前返回多个状态
我有一个flask应用程序的web前端,它在后端执行一些繁重的计算,然后通过JSON将计算出的数据传递到前端以绘制图表 问题是,计算需要几分钟,理想情况下,我希望前端知道请求的完成百分比和状态,而不是静静地坐在那里 JS Ajax请求前端:Javascript 在执行之前返回多个状态,javascript,python,ajax,python-3.x,flask,Javascript,Python,Ajax,Python 3.x,Flask,我有一个flask应用程序的web前端,它在后端执行一些繁重的计算,然后通过JSON将计算出的数据传递到前端以绘制图表 问题是,计算需要几分钟,理想情况下,我希望前端知道请求的完成百分比和状态,而不是静静地坐在那里 JS Ajax请求前端: function runBacktest() { $.ajax({ type: "POST", url: '/backtest', data: {
function runBacktest() {
$.ajax({
type: "POST",
url: '/backtest',
data: {
run_partial: 1,
use_saved_model: false,
saved_model_file: 'model.h5'
},
dataType: "json",
success: function(data) {
//Successful data
},
error: function () {
alert('There was a problem contacting the server.');
}
});
}
Python后端:
@webapp.route('/backtest', methods=['POST'])
def backtest():
print('> Running Backtest...')
"""Calculation code goes on here"""
print('Percent Completed: \r{0:.1f}%'.format(round(pct_done,1)), end='')
"""Serialise each agent instance into a dictionary and put in list to be converted to JSON object"""
agents_serialised = [agent.__dict__ for agent in bt_engine.agents]
return json.dumps(agents_serialised)
问题是,在百分比的每次变化中,我如何将打印在标准输出上的完成百分比之类的内容传递到前端?然后在完成后传递json数据?用于更新前端和后端之间的连接所需的百分比类型。还有对
socket.io
的javascript支持
发布哪些有助于构建此应用程序
我相信你可以用这个来构建,因为我以前做过
示例Python
code:
from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('my percentage event', namespace='/test')
def test_message(message):
#create pertage opertion here
emit('percentage status', {'data': message['data']}, broadcast=True)
$(document).ready(function(){
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
socket.on('percentage status', function(msg) {
//portion for update the percentage
});
});
示例javascript
代码:
from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('my percentage event', namespace='/test')
def test_message(message):
#create pertage opertion here
emit('percentage status', {'data': message['data']}, broadcast=True)
$(document).ready(function(){
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
socket.on('percentage status', function(msg) {
//portion for update the percentage
});
});
这些代码并不完全相同,但可以作为参考 更灵活的方法是将生成器传递给响应。据我所知,这是使用Flask流式传输数据的首选方法。这里有一个非常抽象的例子。寻找我对不同问题的答案,其中我有一个更充实和测试的脚本,在响应中使用生成器
def do_calcs():
while(more_calculations):
"""do your calculations and figure out the percentage."""
agents_serialized = [agent.__dict__ for agent in bt_engine.agents]
yield json.dumps({percent: percent, agents: agents_serialized})
在你的路线上:
return Response(do_calcs(), mimetype='text/json')
如果要这样做,我建议使用为客户端的请求添加进度事件侦听器。这样,JavaScript实际上可以查看请求期间发送的这些JSON对象。