Fix a bug with locally serving images, fix issue #118

This commit is contained in:
Lucas Verney 2018-02-23 16:57:00 +01:00
parent 4ff4510ab7
commit 0b89f27a43

View File

@ -104,22 +104,24 @@ class ImageCache(MemoryCache):
if len(self.map.keys()) > self.max_items: if len(self.map.keys()) > self.max_items:
self.map.popitem(last=False) self.map.popitem(last=False)
# Try to load from local folder
if self.storage_dir:
filepath = os.path.join( filepath = os.path.join(
self.storage_dir, self.storage_dir,
self.compute_filename(url) self.compute_filename(url)
) )
if os.path.isfile(filepath): if os.path.isfile(filepath):
image = PIL.Image.open(filepath) return PIL.Image.open(filepath)
else: # Otherwise, fetch it
req = requests.get(url) req = requests.get(url)
try: try:
req.raise_for_status() req.raise_for_status()
image = PIL.Image.open(BytesIO(req.content)) image = PIL.Image.open(BytesIO(req.content))
if self.storage_dir: if self.storage_dir:
image.save(filepath, format=image.format) image.save(filepath, format=image.format)
return image
except (requests.HTTPError, IOError): except (requests.HTTPError, IOError):
return None return None
return image
def __init__(self, max_items=200, storage_dir=None): def __init__(self, max_items=200, storage_dir=None):
""" """