From 09bd022f5a713c24ab376f0d0901aba436dc151a Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Wed, 27 Oct 2021 09:31:04 +0800 Subject: Separate Lockfile into new class --- jimbrella/database.py | 35 ++++------------------------------- 1 file changed, 4 insertions(+), 31 deletions(-) (limited to 'jimbrella/database.py') 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.""" -- cgit v1.2.3