diff options
author | Frederick Yin <fkfd@fkfd.me> | 2021-10-27 09:31:04 +0800 |
---|---|---|
committer | Frederick Yin <fkfd@fkfd.me> | 2021-10-27 10:10:06 +0800 |
commit | 09bd022f5a713c24ab376f0d0901aba436dc151a (patch) | |
tree | 07aea89c37f1dd0927da9c56df36a7bb4e97932f /jimbrella/database.py | |
parent | cbf419cb79f4a0d06c65167f81f10f503fff391d (diff) |
Separate Lockfile into new class
Diffstat (limited to 'jimbrella/database.py')
-rw-r--r-- | jimbrella/database.py | 35 |
1 files changed, 4 insertions, 31 deletions
diff --git a/jimbrella/database.py b/jimbrella/database.py index 37f6c82..fd8f35c 100644 --- a/jimbrella/database.py +++ b/jimbrella/database.py @@ -1,6 +1,7 @@ import csv import os from datetime import datetime, timedelta +from .lockfile import Lockfile from .utils import human_datetime, human_timedelta from .config import DUE_HOURS from .exceptions import * @@ -43,33 +44,7 @@ class Database: | jForm answer sheet. is blank otherwise. """ self.path = path - - def _lock(self) -> int: - """Create a lockfile for database. - - If the database is called "db.csv", the lockfile, located in the same - directory, would be called "db.csv.lock". - - Returns 1 if the lockfile is successfully created, 0 if the lockfile - already exists (strong hint of unrecovered crash or potential race - condition - caller of this method should abort whatever it is doing) - """ - try: - f = open(self.path + ".lock", "x") - f.close() - return 1 - except FileExistsError: - return 0 - - def _unlock(self) -> None: - """Remove lockfile created by _lock. - - If there is no lockfile, simply ignore. - """ - try: - os.remove(self.path + ".lock") - except FileNotFoundError: - pass + self.lockfile = Lockfile(self.path) def _read(self) -> list: """Deserialize database.""" @@ -106,9 +81,7 @@ class Database: backup = f.read() f.close() - # wait until database is locked for this write - while not self._lock(): - continue + self.lockfile.lock() f = open(self.path, "w") try: @@ -140,7 +113,7 @@ class Database: f.close() raise e - self._unlock() + self.lockfile.unlock() def _update(self, update: dict) -> list: """Update status of one umbrella, and return the entire updated database.""" |