import glob import mimetypes import random import string from http import HTTPStatus from pathlib import Path import filetype from roll import Roll from roll.extensions import simple_server, static from wand.exceptions import MissingDelegateError from wand.image import Image app = Roll() static(app) upload_path = Path("uploaded_images") def _get_random_filename(): random_string = "".join( random.choices( string.ascii_lowercase + string.digits + string.ascii_uppercase, k=15 ) ) file_exists = len(glob.glob(f"{upload_path}/{random_string}.*")) > 0 if file_exists: return _get_random_filename() return random_string @app.route("/") async def home(request, response): response.headers["Content-Type"] = "text/html; charset=utf-8" response.body = open("index.html").read() @app.route("/upload_images", methods=["POST"]) async def upload_images(request, response): images = request.files.list("images") for image in images: random_string = _get_random_filename() tmp_filepath = Path("/tmp/") / random_string tmp_filepath.write_bytes(image.read()) output_type = filetype.guess_extension(str(tmp_filepath)) error = None try: with Image(filename=tmp_filepath) as img: img.strip() with img.convert(output_type) as converted: output_filename = f"{random_string}.{output_type}" output_path = upload_path / output_filename if output_type not in ["gif"]: converted.sequence = [converted.sequence[0]] converted.save(filename=str(output_path)) except MissingDelegateError: error = "Invalid Filetype" finally: if tmp_filepath.exists(): tmp_filepath.unlink() # TODO: deal with errors! response.status = HTTPStatus.FOUND response.headers["Location"] = "/" if __name__ == "__main__": simple_server(app)