friwall/web/db.py

45 lines
1 KiB
Python
Raw Normal View History

2022-01-03 10:33:02 +00:00
import contextlib
import json
import pathlib
import time
2023-05-19 07:03:15 +00:00
def lock(name, timeout=5):
2023-04-07 11:32:26 +00:00
lockfile = pathlib.Path.home() / f'{name}.lock'
2023-05-19 07:03:15 +00:00
for i in range(timeout):
2022-01-03 10:33:02 +00:00
try:
lockfile.symlink_to('/dev/null')
return
except FileExistsError:
time.sleep(1)
raise TimeoutError(f'could not lock {name}')
def unlock(name='db'):
2023-04-07 11:32:26 +00:00
lockfile = pathlib.Path.home() / f'{name}.lock'
2022-01-03 10:33:02 +00:00
lockfile.unlink(missing_ok=True)
@contextlib.contextmanager
def locked(name='db'):
2022-01-03 10:33:02 +00:00
lock(name)
try:
yield name
finally:
unlock(name)
def read(name):
2023-04-07 11:32:26 +00:00
with open(pathlib.Path.home() / f'{name}.json', 'a+', encoding='utf-8') as f:
2022-01-03 10:33:02 +00:00
f.seek(0)
return json.loads(f.read() or '{}')
def write(name, data):
2023-04-07 11:32:26 +00:00
with open(pathlib.Path.home() / f'{name}.json', 'w', encoding='utf-8') as f:
2022-01-03 10:33:02 +00:00
json.dump(data, f, indent=2)
f.close()
def load(name):
with locked():
2022-01-03 10:33:02 +00:00
return read(name)
def save(name, data):
with locked():
2022-01-03 10:33:02 +00:00
write(name, data)