Added options to clear and pre-build cache

This commit is contained in:
Michael Mandl 2018-11-10 16:26:35 +01:00
parent 8a79fda820
commit e20ac0b62e

View file

@ -6,11 +6,16 @@ from pathlib import Path
from PIL import Image from PIL import Image
from time import time from time import time
from hashlib import sha256 from hashlib import sha256
import click
from shutil import rmtree
import config import config
app = Flask(__name__) app = Flask(__name__)
cache_resolution = (1920, 1080)
cache_dir = Path(config.cachedir) / ("%sx%s" % cache_resolution)
@app.route("/") @app.route("/")
def random(): def random():
@ -36,24 +41,60 @@ def random_image():
@app.route("/img/<path:filename>") @app.route("/img/<path:filename>")
def image(filename): def image(filename):
cache_resolution = (1920, 1080) cache_filename = create_cache_file(filename)
cache_dir = Path(config.cachedir) / ("%sx%s" % cache_resolution)
return send_from_directory(cache_dir, cache_filename)
def rm_cachedir():
if Path(config.cachedir).exists():
print("Removing cache dir", config.cachedir)
rmtree(config.cachedir)
def create_cachedir():
if not cache_dir.exists(): if not cache_dir.exists():
print("Creating cache dir", cache_dir) print("Creating cache dir", cache_dir)
cache_dir.mkdir(parents=True) cache_dir.mkdir(parents=True)
original_file_path = Path(config.imgdir) / filename
cache_file = sha256(str(original_file_path.resolve()).encode("utf-8")).hexdigest() def create_cache_file(filename):
create_cachedir()
cache_file = get_cache_filename(filename)
if not (cache_dir / cache_file).exists(): if not (cache_dir / cache_file).exists():
print("Creating cache file", filename) print("Creating cache file", filename)
img = Image.open(original_file_path) img = Image.open(Path(config.imgdir) / filename)
img.thumbnail(cache_resolution) img.thumbnail(cache_resolution)
img.save(cache_dir / cache_file, "JPEG") img.save(cache_dir / cache_file, "JPEG")
return send_from_directory(cache_dir, cache_file) return cache_file
def get_cache_filename(filename):
original_file_path = Path(config.imgdir) / filename
return sha256(str(original_file_path.resolve()).encode("utf-8")).hexdigest()
def pre_cache_images():
imgdir = Path(config.imgdir)
for image_file in sorted(imgdir.glob("*.jpg")):
create_cache_file(image_file.relative_to(imgdir))
@click.command()
@click.option("--build-cache", is_flag=True, default=False, help="pre-cache images")
@click.option(
"--clear-cache", is_flag=True, default=False, help="clear cache directory"
)
def run_slider(build_cache, clear_cache):
if clear_cache:
rm_cachedir()
if build_cache:
pre_cache_images()
app.run()
if __name__ == "__main__": if __name__ == "__main__":
app.run() run_slider()