Abdullah Awan
Abdullah Awan

Reputation: 11

flask socketio with database communication

what i am trying to do is the next:

  1. First connection is made by the cliente ("connect")
  2. Then from the Python, i call the function which depending on the info in database, makes an emmit to another "socket" (test).

But my problem is, when there is any register in the database, it makes an emmit to test and shows "You have something!", but when i delete the info from the database and there is no register in database, this does not work. I have to manually resfresh the pade so it shows the ""You have nothing!". Is there any better way to do it? Without resfreshing the page? Suppously this is a full-duplex. Thanks in advance!

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>

Upvotes: 0

Views: 2960

Answers (1)

Alex
Alex

Reputation: 2174

Executing your handle_message in a separate thread in a loop and send data to the client could be one of the options.

Here is a basic idea. Look at 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()

Upvotes: 1

Related Questions