从视图中发出websocket消息 [英] Emit websocket message from a view
问题描述
我正在使用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>
< script type =text / javascriptcharset =utf-8>
$(document).ready(function(){
namespace ='/ test';
var socket = io.connect(location.protocol +'//'+ document.domain + ':'+ location.port + namespace);
//这将被服务器调用
//匿名函数将被执行并且跨越idview将被更新
socket .on('my_response',function(msg){
$('span#view')。text(msg.count);
});
});
< / script>
< / head>
< body>
< h1> Flask-SocketIO简单示例< / h1>
< p>服务器计数器:< span id =view>< / span>< / p>
< / a>
< / body>
< / html>
当您使用 python app.py
,并访问 http://127.0.0.1:5050 ,那么你应该看到插槽的行动。
该演示的工作版本可用这里
I am playing around with websockets in order to see if I can replace polling updates to a project. I am using Flask-Sockets and I want to emit an update through a Flask view.
For example
from flask import Flask
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/echo')
def echo_socket(ws):
while True:
message = ws.receive()
ws.send(message)
@app.route('/')
def hello():
# here I want to emit a message like ws.send(message)
return 'Hello World!'
I looked around and I didnt find anything similar. Is this thing possible?
THIS IS VERY VERY SIMPLE DEMO EXAMPLE
In the below example, on every 2 seconds, the server send message to the client with updated count. First parameter of emit function tells which function to call on client side.
app.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None
def background_thread():
count = 0
while True:
socketio.sleep(2)
count += 1
socketio.emit('my_response',
{'data': 'Message from server', 'count': count},
namespace='/test')
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})
if __name__ == '__main__':
socketio.run(app, debug=True, host='0.0.0.0', port=5050)
On your client side you will have to use this. In this example I have included CDN. Similarly for demo purpose I have used jquery.
templates/index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Flask-SocketIO Test</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/test';
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
// This will be called by server.
// Anonymous function will be executed and span with id "view" will be updated
socket.on('my_response', function(msg) {
$('span#view').text(msg.count);
});
});
</script>
</head>
<body>
<h1>Flask-SocketIO Simple Example</h1>
<p>Counter at server: <span id="view"></span></p>
</a>
</body>
</html>
When you run this using python app.py
, and visit http://127.0.0.1:5050, then you should see the sockets in action.
A working version of the demo is available here
这篇关于从视图中发出websocket消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!