Skip to content

Commit a561ac9

Browse files
committed
Raise error during instantiation when FileCache dependency lockfile is missing
This prevents the same error from being printed to stdout when importing the RedisCache class and not using FileCache at all.
1 parent 9ac52cd commit a561ac9

File tree

3 files changed

+21
-28
lines changed

3 files changed

+21
-28
lines changed

cachecontrol/caches/__init__.py

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,2 @@
1-
from textwrap import dedent
2-
3-
try:
4-
from .file_cache import FileCache # noqa
5-
except ImportError:
6-
notice = dedent('''
7-
NOTE: In order to use the FileCache you must have
8-
lockfile installed. You can install it via pip:
9-
pip install lockfile
10-
''')
11-
print(notice)
12-
13-
14-
try:
15-
import redis # noqa
16-
from .redis_cache import RedisCache # noqa
17-
except ImportError:
18-
pass
1+
from .file_cache import FileCache # noqa
2+
from .redis_cache import RedisCache # noqa

cachecontrol/caches/file_cache.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import hashlib
22
import os
3-
4-
from lockfile import LockFile
5-
from lockfile.mkdirlockfile import MkdirLockFile
3+
import warnings
4+
from textwrap import dedent
65

76
from ..cache import BaseCache
87
from ..controller import CacheController
@@ -55,19 +54,29 @@ def __init__(self, directory, forever=False, filemode=0o0600,
5554
if use_dir_lock is not None and lock_class is not None:
5655
raise ValueError("Cannot use use_dir_lock and lock_class together")
5756

58-
if use_dir_lock:
59-
lock_class = MkdirLockFile
60-
61-
if lock_class is None:
62-
lock_class = LockFile
57+
try:
58+
from lockfile import LockFile
59+
from lockfile.mkdirlockfile import MkdirLockFile
60+
except ImportError:
61+
notice = dedent("""
62+
NOTE: In order to use the FileCache you must have
63+
lockfile installed. You can install it via pip:
64+
pip install lockfile
65+
""")
66+
raise ImportError(notice)
67+
else:
68+
if use_dir_lock:
69+
lock_class = MkdirLockFile
70+
71+
elif lock_class is None:
72+
lock_class = LockFile
6373

6474
self.directory = directory
6575
self.forever = forever
6676
self.filemode = filemode
6777
self.dirmode = dirmode
6878
self.lock_class = lock_class
6979

70-
7180
@staticmethod
7281
def encode(x):
7382
return hashlib.sha224(x.encode()).hexdigest()

tests/test_regressions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44

55
from cachecontrol import CacheControl
6-
from cachecontrol.caches.file_cache import FileCache
6+
from cachecontrol.caches import FileCache
77
from cachecontrol.filewrapper import CallbackFileWrapper
88
from requests import Session
99

0 commit comments

Comments
 (0)