与数据库通信的烧瓶socketio

时间:2018-03-29 09:28:41

标签: flask websocket socket.io flask-socketio

我想要做的是下一个:

  1. 第一个连接由cliente(“connect”)
  2. 完成
  3. 然后从Python中,我根据数据库中的信息调用函数,向另一个“套接字”(测试)发出声音。
  4. 但我的问题是,当数据库中有任何寄存器时,它会发出测试并显示“你有东西!”,但是当我从数据库中删除信息并且数据库中没有寄存器时,不起作用。我必须手动重新刷新pade所以它显示“”你什么都没有!“。有没有更好的方法呢?没有重新刷新页面?这是一个全双工。提前感谢!

    的Python:

    from flask import Flask, render_template
    from flask_socketio import SocketIO, emit, send
    from flask_cors import CORS
    import MySQLdb
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app)
    CORS(app)
    
    @socketio.on('connect')
    def con():
        handle_message()
    
    def handle_message():
        db = MySQLdb.connect("localhost","root","","sitandorder" )
        cursor = db.cursor()
        cursor.execute("SELECT * FROM historico_pedido")
        data = cursor.fetchall()
        print(len(data))
        if len(data) >= 1:
            emit ("test" ,"You have something!")
        else:
            emit ("test" ,"You have nothing!")
        db.close()
    
    
    if __name__ == '__main__':
        socketio.run(app, debug=True, host='127.0.0.1', port=5000 )
    

    使用Javascript:

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js">
        </script>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <script type="text/javascript">
          $(document).ready(function(){
              var socket = io.connect('http://127.0.0.1:5000');
              socket.on('connect', function(){
                console.log("Connected"); // Make the connection!
              });
              socket.on('test', function(arg){
                console.log(arg); //Here i show what i get from the handle_message() of python
              })
          });
        </script>
      </body>
    </html>
    

1 个答案:

答案 0 :(得分:0)

在循环中的单独线程中执行handle_message并将数据发送到客户端可能是其中一个选项。

这是一个基本想法。看看Python concurency options

@socketio.on('connect')
def con():
    thread = Thread(target=background_task)
    thread.start()

def background_task():
    while True:
       time.sleep(1)
       handle_message()


def handle_message():
    db = MySQLdb.connect("localhost","root","","sitandorder" )
    cursor = db.cursor()
    cursor.execute("SELECT * FROM historico_pedido")
    data = cursor.fetchall()
    print(len(data))
    if len(data) >= 1:
        emit ("test" ,"You have something!")
    else:
        emit ("test" ,"You have nothing!")
    db.close()