Python access variable inside a callback from library

Viewed 16

I am creating a websocket inside python using a third party broker library.

The library states that I need to provide a callback function, which will be called, anytime a new message is received. This all works, but now I am trying to insert the data in database when my callback is called, but I am not able to use the existing DbHandle object that I created in my main app.

main.py

from db_queries import addToDb
from brokerConnection import createBrokerWebSocket

app = Flask(__name__)

socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app, support_credentials=True)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'mydb'

dbHandle = MySQL(app)

@app.route('/myFun1', methods = ['GET'])
def myFun1():
    addToDb(dbHandle)
    createBrokerWebSocket(dbHandle)

db_queries.py

def addToDb(dbHandle, userId, accessToken):
    print(dbHandle.connection)
    
    cursor = dbHandle.connection.cursor()
    cursor.execute("my_sql")
    dbHandle.connection.commit()
    cursor.close()

brokerConnection.py

from db_queries import addToDb
dbHandlee = None

def createBrokerWebSocket(dbHandleIn):
    //setting this here, so I can use it in my callback that gets triggered from lib
    global dbHandlee
    dbHandlee = dbHandleIn
    //After this, code to connect via websocket to broker.

def onMessageCallback():
    addToDb(dbHandlee)

The problem is that, print(dbHandle.connection) this line in db_queries prints a connection object when myFun1 -> addToDb is called, but it prints None when my callback function calls it.

Also, if I do print(dbHandle), instead of print(dbHandle.connection), then in that case, the same object is printed.

Can someone help me understand what is the problem, and how can I go about fixing it?

0 Answers
Related