2014-11-01 17 views
4

我正在使用websockets來查看是否可以將輪詢更新替換爲項目。我正在使用Flask-Sockets,我想通過Flask視圖發出更新。從視圖中發出websocket消息

例如

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

我環顧四周,我沒有發現類似的事情。這可能嗎?

+0

曾經找到答案?我也在尋找這 – 2015-11-23 14:13:51

+0

可悲的是我沒有。我決定使用Server Sent Events,因爲websockets不是我所需要的。 – kechapito 2015-12-01 16:05:36

+0

我在這裏得到了答案:):https://stackoverflow.com/a/47526225/111510 – tiktuk 2017-11-28 15:21:26

回答

1

這是非常非常簡單的演示實施例

在下面的例子中,每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