在Flask中使用socketio.on()渲染新模板 [英] Render a new template with socketio.on() in Flask

查看:235
本文介绍了在Flask中使用socketio.on()渲染新模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照以下方式做些事情:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆