Render a new template with socketio.on() in Flask
Question:
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.
Answers:
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.
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.
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.