From b859fece8829a1740396e35632360f731a34768e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Sun, 15 Sep 2024 20:46:02 +0200 Subject: [PATCH] Introduce image request query parameter for filtering and selection (#2) * Add selection ability using image query parameter the selections is the index of the list of images, where 0 is the first image. `os.listdir` is asumed to always sort the list the same. - if no selection is provided, take random image from image collection (like main) - if 1 selection is provided, return the nth image from collection - if 2 or more selections are provided, take random item from the selection and return the image at that index. * Handle bad selection input - Nondigit selections returns HTTP 401 - exclude indexes out of range (0--collection length) --- wsgi.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/wsgi.py b/wsgi.py index c3fca35..fe6ef40 100644 --- a/wsgi.py +++ b/wsgi.py @@ -21,7 +21,23 @@ def get_cropped_image(x, y, grey=False, retries=0): """crops a random image from collection""" if retries > 10: return None - im_src = random.choice(os.listdir("./images")) + options = os.listdir("./images") + try: + selection = list( + filter( + lambda i: i in range(0, len(options)), + map(int, request.args.getlist("image")), + ) + ) + except ValueError: + return None + match len(selection): + case 0: + im_src = random.choice(options) + case 1: + im_src = options[selection[0]] + case _: + im_src = options[random.choice(selection)] im = Image.open(f"images/{im_src}") out = BytesIO() max_x, max_y = im.size