Jan-17-2020, 09:29 PM
Hi everybody,
I'm writing a module for a program and the purpose is to check a row in a db- if "new" run some function.
I was pretty sure this logic would work (and was pretty proud of myself), alas, it doesn't work. It's supposed to run every 2 seconds to compare the newest row as a db "listener", of sorts.
My logic:
connect to db, query for the newest row, compare that row with variable, if not equal, run function, store newest row to variable, else close.
Here's the code:
This confuses me for 2 reasons.
A) I thought I set last_sent to '' as a global variable/object.
B) In order for my comparison logic to work, I can't set last_sent within the sendListener() function before the if/else!
Is there a better way of implementing this type of thing?
What am I doing wrong here?
Thank you!
I'm writing a module for a program and the purpose is to check a row in a db- if "new" run some function.
I was pretty sure this logic would work (and was pretty proud of myself), alas, it doesn't work. It's supposed to run every 2 seconds to compare the newest row as a db "listener", of sorts.
My logic:
connect to db, query for the newest row, compare that row with variable, if not equal, run function, store newest row to variable, else close.
Here's the code:
from Logger import Logger from sendSMS import sendSMS from Needles import dbUser, dbHost, dbPassword, pull_stmt import pyodbc import time #set last_sent to something last_sent = '' def sendListener(): #connect to db cnxn = pyodbc.connect('UID='+dbUser+';PWD='+dbPassword+';DSN='+dbHost) cursor = cnxn.cursor() #run query to pull newest row cursor.execute(pull_stmt) results = cursor.fetchone() #if query results different from results stored in last_sent, run function. #then set last_sent object to the query results for next comparison. if results != last_sent: sendSMS() last_sent = results else: cnxn.close() # a loop to run the check every 2 seconds- as to lessen cpu usage def sleepLoop(): while 0 == 0: sendListener() time.sleep(2.0) sleepLoop()The error I'm getting is that 'local variable last_sent' referenced before assignment.
This confuses me for 2 reasons.
A) I thought I set last_sent to '' as a global variable/object.
B) In order for my comparison logic to work, I can't set last_sent within the sendListener() function before the if/else!
Is there a better way of implementing this type of thing?
What am I doing wrong here?
Thank you!