Prefer recent images

This commit is contained in:
Michael Mandl 2018-11-08 00:10:08 +01:00
parent e4de3b3148
commit 41d7c104af

View file

@ -4,6 +4,7 @@ from flask import Flask, render_template, send_from_directory, redirect, url_for
from random import choice from random import choice
from pathlib import Path from pathlib import Path
from PIL import Image from PIL import Image
from time import time
import config import config
@ -18,16 +19,26 @@ def random():
@app.route("/random_image/") @app.route("/random_image/")
def random_image(): def random_image():
imgdir = Path(config.imgdir) imgdir = Path(config.imgdir)
last_modified_time, last_modified_file = max(
(f.stat().st_mtime, f) for f in imgdir.glob("*.jpg")
)
if time() - last_modified_time <= 60:
selected_image = last_modified_file.relative_to(imgdir)
else:
images = list(imgdir.glob("*.jpg")) images = list(imgdir.glob("*.jpg"))
selected_image = choice(images).relative_to(imgdir) selected_image = choice(images).relative_to(imgdir)
return redirect(url_for("image", filename=selected_image)) return redirect(url_for("image", filename=selected_image))
@app.route("/img/<path:filename>") @app.route("/img/<path:filename>")
def image(filename): def image(filename):
scaled_img_dir = Path(config.imgdir) / ".slider" / "fhd" scaled_img_dir = Path(config.imgdir) / ".slider" / "fhd"
if not scaled_img_dir.exists(): if not scaled_img_dir.exists():
scaled_img_dir.mkdir(parents=True) scaled_img_dir.mkdir(parents=True)
if not (scaled_img_dir / filename).exists(): if not (scaled_img_dir / filename).exists():
img = Image.open(Path(config.imgdir) / filename) img = Image.open(Path(config.imgdir) / filename)
img.thumbnail((1920, 1080)) img.thumbnail((1920, 1080))