加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从视图中发出websocket消息

发布时间:2020-12-20 13:45:32 所属栏目:Python 来源:网络整理
导读:我正在玩websockets以查看是否可以替换项目的轮询更新.我正在使用Flask-Sockets,我想通过Flask视图发出更新. 例如 from flask import Flaskfrom flask_sockets import Socketsapp = Flask(__name__)sockets = Sockets(app)@sockets.route('/echo')def echo_s
我正在玩websockets以查看是否可以替换项目的轮询更新.我正在使用Flask-Sockets,我想通过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)

在您的客户端,您将不得不使用this.在此示例中,我已包含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>

当你使用python app.py运行它,并访问http://127.0.0.1:5050时,你应该看到套接字在运行.

该演示的工作版本可在here获得

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读