【发布时间】:2019-10-17 06:04:46
【问题描述】:
我正在从我的 python 脚本连接到 MySQL,订阅来自 mqtt 代理的主题,并且每当我收到数据时,我都会存储数据。
代码
import mysql.connector
connection = mysql.connector.connect(host='localhost',database='db',user='',
password='',auth_plugin='mysql_native_password')
sql_insert_query = """ #INSERT query
cursor = connection.cursor()
def on_message(client, userdata, message):
print("message received ")
msg = json.loads(message.payload.decode("utf-8"))
#processing of message
cursor.execute(sql_insert_query,processed_msg)
connection.commit()
print('inserted in db')
def on_connect(client, userdata, flags, rc):
print("Subscribing to topic","topic")
client.subscribe("topic")
broker_address=""
port = 8888
client = mqtt.Client(clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
client.loop_forever() #stop the loop
因此,当 mqtt 收到任何消息时,使用此代码保存数据。但是有时 mqtt 超过 8 小时没有收到数据,然后又开始接收数据。在这种情况下,脚本不会存储 8 小时左右后的数据。我相信某种超时正在发生。因为当我再次运行脚本时,数据存储在 mysql db 中。有人可以帮我理解这是什么类型的超时或如何解决这个问题吗?
谢谢
【问题讨论】:
-
您在顶部连接一次到数据库可能连接超时您每次收到消息时连接到数据库并在您的
on_message回调中完成时关闭 -
谢谢!!知道可能是什么原因
-
在
on_message回调中围绕数据库更新代码添加一个try/expect块。这将向您显示错误,因为 MQTT 客户端在其自己的 try/expect 块中调用了on_message函数,该块丢弃了所有抛出的异常。
标签: python mysql mqtt mysql-python paho