Skip to content

Commit

Permalink
wip: Write custom flock context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
kairstenfay committed Sep 17, 2020
1 parent 309caae commit 06b84f8
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/id3c/cli/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import click
import pickle
import logging
from io import IOBase
from functools import wraps
from typing import Optional
from cachetools import TTLCache
from contextlib import contextmanager
from fcntl import flock, LOCK_EX, LOCK_UN
from id3c.db.session import DatabaseSession


Expand Down Expand Up @@ -125,7 +127,9 @@ def pickled_cache(filename: str = None) -> TTLCache:
LOG.info(f"Loading cache from «{filename}»")
try:
with open(filename, "rb") as file:
lock_file(file)
cache = pickle.load(file)

except FileNotFoundError:
LOG.warning(f"Cache file «{filename}» does not exist; starting with empty cache.")
cache = empty_cache
Expand All @@ -142,3 +146,17 @@ def pickled_cache(filename: str = None) -> TTLCache:
if filename:
with open(filename, "wb") as file:
pickle.dump(cache, file)


@contextmanager
def lock_file(file_object: IOBase):
"""
Context manager for locking/unlocking a given :class:`IOBase` *file_object*.
"""
# Apply POSIX-style, exclusive lock
flock(file_object, LOCK_EX)

yield

# Remove the lock
flock(file_object, LOCK_UN)

0 comments on commit 06b84f8

Please sign in to comment.