Render a new template with socketio.on() in Flask

五迷三道 提交于 2020-02-03 13:23:04

问题


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)

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.


回答1:


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')})

Then in your client:

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.



来源:https://stackoverflow.com/questions/23835432/render-a-new-template-with-socketio-on-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!