This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
WebSlider/slider.py

54 lines
1.3 KiB
Python
Raw Normal View History

#!/usr/bin/python3
from flask import Flask, render_template, send_from_directory, redirect, url_for
from random import choice
from pathlib import Path
from PIL import Image
2018-11-07 23:10:08 +00:00
from time import time
import config
app = Flask(__name__)
2018-10-29 19:35:45 +00:00
@app.route("/")
def random():
2018-11-05 21:01:57 +00:00
return render_template("random.html", refresh=config.refresh)
2018-10-29 19:35:45 +00:00
@app.route("/random_image/")
def random_image():
2018-11-08 08:00:00 +00:00
img_glob = "*jpg"
2018-11-07 22:43:29 +00:00
imgdir = Path(config.imgdir)
2018-11-07 23:10:08 +00:00
last_modified_time, last_modified_file = max(
2018-11-08 08:00:00 +00:00
(f.stat().st_mtime, f) for f in imgdir.glob(img_glob)
2018-11-07 23:10:08 +00:00
)
if time() - last_modified_time <= 60:
selected_image = last_modified_file.relative_to(imgdir)
else:
2018-11-08 08:00:00 +00:00
images = list(imgdir.glob(img_glob))
2018-11-07 23:10:08 +00:00
selected_image = choice(images).relative_to(imgdir)
2018-11-07 22:43:29 +00:00
return redirect(url_for("image", filename=selected_image))
@app.route("/img/<path:filename>")
def image(filename):
2018-11-08 08:00:00 +00:00
cache_resolution = (1920, 1080)
cache_dir = Path(config.cachedir) / ("%sx%s" % cache_resolution)
2018-11-07 23:10:08 +00:00
2018-11-08 08:00:00 +00:00
if not cache_dir.exists():
cache_dir.mkdir(parents=True)
2018-11-07 23:10:08 +00:00
2018-11-08 08:00:00 +00:00
if not (cache_dir / filename).exists():
img = Image.open(Path(config.imgdir) / filename)
2018-11-08 08:00:00 +00:00
img.thumbnail(cache_resolution)
img.save(cache_dir / filename)
2018-11-08 08:00:00 +00:00
return send_from_directory(cache_dir, filename)
if __name__ == "__main__":
app.run()