Python 从视图发出websocket消息

Python 从视图发出websocket消息,python,flask,flask-sockets,Python,Flask,Flask Sockets,我正在玩WebSocket,看看是否可以替换项目的轮询更新。我正在使用Flask套接字,希望通过Flask视图发出更新 比如说 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

我正在玩WebSocket,看看是否可以替换项目的轮询更新。我正在使用Flask套接字,希望通过Flask视图发出更新

比如说

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

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

这是一个非常简单的演示示例

在下面的示例中,服务器每2秒向客户端发送一条更新计数的消息。emit函数的第一个参数指示在客户端调用哪个函数

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)
在客户端,您必须使用。在这个例子中,我包括了CDN。同样,出于演示目的,我使用了jquery

模板/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>

烧瓶冲击试验
$(文档).ready(函数(){
名称空间='/test';
var socket=io.connect(location.protocol+'/'+document.domain+':'+location.port+名称空间);
//这将由服务器调用。
//将执行匿名函数,并更新id为“view”的span
socket.on('my_response',函数(msg){
$('span#view').text(msg.count);
});
});
一个简单的例子
服务器上的计数器:

当您使用
python app.py运行此程序并访问时,您应该会看到套接字正在运行


演示的工作版本可用

找到答案了吗?我在找这个,可惜我没有。我决定使用服务器发送的事件,因为WebSocket不是我所需要的。我在这里得到了答案:):