Write to FS on every POST to prevent data loss on server crash
This commit is contained in:
parent
64ca89eefb
commit
99da9da68a
|
@ -20,7 +20,9 @@ def startup():
|
||||||
fd = open(filename)
|
fd = open(filename)
|
||||||
data = json.load(fd)
|
data = json.load(fd)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
pass
|
print("DB file not found, creating on POST/write.")
|
||||||
|
finally:
|
||||||
|
fd.close()
|
||||||
|
|
||||||
|
|
||||||
@app.route('/db/<id>', methods = ['GET'])
|
@app.route('/db/<id>', methods = ['GET'])
|
||||||
|
@ -45,20 +47,15 @@ def post():
|
||||||
id = generateNewKey()
|
id = generateNewKey()
|
||||||
data[id] = request.data.decode('UTF-8')
|
data[id] = request.data.decode('UTF-8')
|
||||||
|
|
||||||
return id, 201
|
|
||||||
|
|
||||||
|
|
||||||
def dumpDB():
|
|
||||||
|
|
||||||
if len(data) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
fd = open(filename, 'w+')
|
fd = open(filename, 'w+')
|
||||||
json.dump(data, fd)
|
json.dump(data, fd, indent=2)
|
||||||
|
except e:
|
||||||
|
print("Failed to open/create DB file for writing:", e)
|
||||||
finally:
|
finally:
|
||||||
fd.close()
|
fd.close()
|
||||||
|
|
||||||
|
return id, 201
|
||||||
|
|
||||||
|
|
||||||
startup()
|
startup()
|
||||||
atexit.register(dumpDB)
|
|
||||||
|
|
Loading…
Reference in New Issue