【问题标题】:flask socketio with database communication带有数据库通信的烧瓶 socketio
【发布时间】:2018-03-29 09:28:41
【问题描述】:

接下来我要做的是:

  1. 第一个连接是由客户端建立的(“连接”)
  2. 然后从 Python 中调用函数,该函数根据数据库中的信息向另一个“套接字”(测试)发出 emmit。

但是我的问题是,当数据库中有任何寄存器时,它会发出一个测试并显示“你有东西!”,但是当我从数据库中删除信息并且数据库中没有寄存器时,这个不起作用。我必须手动重新刷新 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>

【问题讨论】:

    标签: flask websocket socket.io flask-socketio


    【解决方案1】:

    在一个单独的线程中循环执行您的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()
    

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2023-04-06
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多