Fixed database file race condition

This commit is contained in:
bj
2020-10-16 11:47:37 +02:00
parent 682c0116dd
commit b13fbf536f
+8 -3
View File
@@ -1,20 +1,23 @@
import json
import os
import threading
import paho.mqtt.subscribe as mqtt
database_file = "clients.json"
database_lock = threading.Lock()
# noinspection PyUnusedLocal
def update_client_record(client, userdata, message):
database_lock.acquire()
if not os.path.exists(database_file):
with open(database_file, 'w') as database_blank:
database_blank.write("{}")
json.dump({}, database_blank)
with open(database_file, 'r') as infile:
database = json.loads(infile.read())
database = json.load(infile)
payload = message.payload.decode('utf-8')
response = json.loads(payload)
@@ -24,6 +27,8 @@ def update_client_record(client, userdata, message):
with open(database_file, 'w') as outfile:
json.dump(database, outfile)
database_lock.release()
def subscribe(broker_hostname, broker_port, topic="torch", tls=None, auth=None):
mqtt.callback(update_client_record,