Fixed database file race condition

This commit is contained in:
B.J. Dweck 2020-10-16 11:47:37 +02:00
parent 682c0116dd
commit b13fbf536f

View File

@ -1,20 +1,23 @@
import json import json
import os import os
import threading
import paho.mqtt.subscribe as mqtt import paho.mqtt.subscribe as mqtt
database_file = "clients.json" database_file = "clients.json"
database_lock = threading.Lock()
# noinspection PyUnusedLocal # noinspection PyUnusedLocal
def update_client_record(client, userdata, message): def update_client_record(client, userdata, message):
database_lock.acquire()
if not os.path.exists(database_file): if not os.path.exists(database_file):
with open(database_file, 'w') as database_blank: with open(database_file, 'w') as database_blank:
database_blank.write("{}") json.dump({}, database_blank)
with open(database_file, 'r') as infile: with open(database_file, 'r') as infile:
database = json.loads(infile.read()) database = json.load(infile)
payload = message.payload.decode('utf-8') payload = message.payload.decode('utf-8')
response = json.loads(payload) response = json.loads(payload)
@ -24,6 +27,8 @@ def update_client_record(client, userdata, message):
with open(database_file, 'w') as outfile: with open(database_file, 'w') as outfile:
json.dump(database, outfile) json.dump(database, outfile)
database_lock.release()
def subscribe(broker_hostname, broker_port, topic="torch", tls=None, auth=None): def subscribe(broker_hostname, broker_port, topic="torch", tls=None, auth=None):
mqtt.callback(update_client_record, mqtt.callback(update_client_record,