|
3 | 3 | from datetime import timedelta |
4 | 4 | from io import BytesIO |
5 | 5 | from os.path import join |
| 6 | +from sqlite3 import OperationalError |
6 | 7 | from urllib.error import URLError |
7 | 8 | from urllib.parse import urlparse |
8 | 9 | from urllib.request import urlopen |
9 | 10 |
|
| 11 | +import requests |
10 | 12 | from AnyQt.QtCore import QStandardPaths |
11 | 13 | from PIL import ImageFile |
12 | 14 | from PIL.Image import LANCZOS |
|
19 | 21 |
|
20 | 22 |
|
21 | 23 | class ImageLoader: |
22 | | - def __init__(self): |
| 24 | + _session = None |
| 25 | + |
| 26 | + @property |
| 27 | + def session(self): |
| 28 | + if self._session is not None: |
| 29 | + return self._session |
| 30 | + |
23 | 31 | cache_dir = QStandardPaths.writableLocation(QStandardPaths.CacheLocation) |
24 | 32 | cache_path = join(cache_dir, "networkcache", "image_loader.sqlite") |
25 | | - self._session = CachedSession( |
26 | | - cache_path, |
27 | | - backend="sqlite", |
28 | | - cache_control=True, |
29 | | - expire_after=timedelta(days=1), |
30 | | - stale_if_error=True, |
31 | | - ) |
| 33 | + try: |
| 34 | + self._session = CachedSession( |
| 35 | + cache_path, |
| 36 | + backend="sqlite", |
| 37 | + cache_control=True, |
| 38 | + expire_after=timedelta(days=1), |
| 39 | + stale_if_error=True, |
| 40 | + ) |
| 41 | + except OperationalError as ex: |
| 42 | + # if no permission to write in dir or read cache file return regular session |
| 43 | + log.info( |
| 44 | + f"Cache file creation/opening failed with: '{str(ex)}'. " |
| 45 | + "Using requests.Session instead of cached session." |
| 46 | + ) |
| 47 | + self._session = requests.Session() |
| 48 | + return self._session |
32 | 49 |
|
33 | 50 | def load_image_or_none(self, file_path, target_size=None): |
34 | 51 | if file_path is None: |
@@ -66,7 +83,7 @@ def _load_image_from_url_or_local_path(self, file_path): |
66 | 83 | urlparts = urlparse(file_path) |
67 | 84 | if urlparts.scheme in ("http", "https"): |
68 | 85 | try: |
69 | | - file = BytesIO(self._session.get(file_path).content) |
| 86 | + file = BytesIO(self.session.get(file_path).content) |
70 | 87 | except RequestException: |
71 | 88 | log.warning("Image skipped", exc_info=True) |
72 | 89 | return None |
|
0 commit comments