从视图中发出websocket消息 [英] Emit websocket message from a view

查看:240
本文介绍了从视图中发出websocket消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用websockets来查看是否可以将轮询更新替换为一个项目。我使用Flask-Sockets,我想通过Flask视图发布更新。



例如

 from flask import Flask 
from flask_sockets import Sockets
$ b $ app = Flask(__ name__)
sockets =套接字(应用程序)

@ sockets.route('/ echo')
def echo_socket(ws):
而True:
message = ws.receive()
ws.send(message )

@ app.route('/')
def hello():
#在这里我想发出一个消息ws.send(message)
return'Hello World!'

我环顾四周,没有发现任何类似的东西。这是可能的吗?

解决方案

这是非常简单的演示示例



在下面的示例中,服务器每隔2秒向客户端发送更新计数的消息。 emit函数的第一个参数告诉客户端调用哪个函数。
$ b $ p app.py

 从flask导入烧瓶,render_template $ b $ from flask_socketio导入SocketIO,发出


app =烧瓶(__ name__)
app.config ['SECRET_KEY'] ='secret!'
socketio = SocketIO(应用程序)
线程=无

$ b $ def background_thread():
count = 0
而真:
socketio.sleep(2)
count + = 1
socketio.emit('my_response',
{'data' :'从服务器发送','count':count},
namespace ='/ test')


@ app.route('/')
def index():
return render_template('index.html')


@ socketio.on('connect',namespace ='/ test')
def test_connect():
全局线程
如果线程为None:
thread = socketio.start_background_task(targ et = background_thread)
发出('my_response',{'data':'Connected','count':0})


if __name__ =='__main__':
socketio.run(app,debug = True,host ='0.0.0.0',port = 5050)

在您的客户端,您将不得不使用这个。在这个例子中,我包含了CDN。同样,为了演示的目的,我已经使用jQuery。



模板/ index.html

 <!DOCTYPE HTML> 
< html>
< head>
< title> Flask-SocketIO Test< / title>
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆