Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

python - 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)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...