annals.jsonstore#
A MutableMapping kept in one JSON file, safe with several server processes.
The owner’s tags (annals.tags) and each reader’s listening progress
(annals.listening) are small, server-side records that the page changes one entry at
a time. JsonFileStore is that one mechanism: a JSON object in a file, written
atomically under an exclusive flock, re-read whenever another process changed it, and
never broken by a damaged file (it reads as empty and is kept aside at the next write).
A subclass says what a valid value is (JsonFileStore.valid()) and how a value is
cleaned before it is stored (JsonFileStore.clean()). JsonFileStore.modify()
changes one entry from its current value under the lock, so two devices reporting at once
never lose each other’s change.
>>> import tempfile, pathlib
>>> s = JsonFileStore(pathlib.Path(tempfile.mkdtemp()) / "x.json")
>>> s["a"] = {"n": 1}
>>> s.modify("a", lambda v: {"n": (v or {}).get("n", 0) + 1})
{'n': 2}
>>> dict(s)
{'a': {'n': 2}}
Module Attributes
the suffix a damaged file is kept under, so a hand edit gone wrong can be recovered |
Classes
|
|
- annals.jsonstore.DAMAGED_SUFFIX = '.damaged'#
the suffix a damaged file is kept under, so a hand edit gone wrong can be recovered
- class annals.jsonstore.JsonFileStore(path)[source]#
Bases:
MutableMapping{key: value}in one JSON file, re-read when another process changed it.A write takes an exclusive
flockon<file>.lock, re-reads the file, changes it and replaces it atomically. A read re-reads the file whenever its inode, size or mtime changed (every write makes a new inode).labelnames the store in log messages.- modify(key, change)[source]#
Set
keytochange(current value or None), atomically; returns the stored value.changereturningNonedeletes the entry (and returnsNone).- Return type: