在 Flask 中使用 socketio.on() 渲染一个新模板 [英] Render a new template with socketio.on() in Flask
问题描述
我正在尝试按照以下方式做一些事情:
I'm trying to do something along these lines:
from flask import Flask, render_template, redirect, url_for
from flask.ext.socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/start')
def start():
return render_template('start.html')
@app.route('/new_view')
def new_view():
return render_template('new_view.html')
@socketio.on('change_view')
def change_view(message):
return redirect(url_for('new_view'))
if __name__ == "__main__":
socketio.run(app, host='127.0.0.1', port=8080)
基本上我希望它在收到来自客户端的change_view"消息时重定向.现在,在我单击触发 socket.emit('change_view', message)
调用的按钮后,它会进入 change_view()
函数,以便该部分工作.它根本就不会重定向或进入 new_view()
函数(即,如果我在 new_view()
中放置了一个打印语句,它就不会打印).但它也没有给我任何错误.我是套接字的新手,所以我猜测存在一些根本性的误解.
Basically I want it to redirect if it gets the 'change_view' message from the client. Right now it gets to the change_view()
function after I click a button that triggers the socket.emit('change_view', message)
call, so that part works. It just doesn't redirect or get into the new_view()
function at all (i.e. if I put a print statement in new_view()
it doesn't print). But it also doesn't give me any errors. I am new to sockets so I'm guessing there's some fundamental misunderstanding going on.
推荐答案
是的,socket.io 不是这样工作的.您可以发送消息告诉客户端加载新页面.
Yeah, socket.io doesn't work like that. You can send a message telling the client to load a new page.
emit('redirect', {'url': url_for('new_view')})
然后在您的客户端:
socket.on('redirect', function (data) {
window.location = data.url;
});
但不清楚为什么您需要在这个特定示例中访问服务器.
But it's not clear why you need to hit the server at all for this particular example.
这篇关于在 Flask 中使用 socketio.on() 渲染一个新模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!