From bae4953097806602fcf45a59618b6d2dd6aa2043 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Sat, 30 Oct 2021 17:29:28 -0700 Subject: [PATCH] Move give_theme_cookie to flasktools. --- voussoirkit/flasktools.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/voussoirkit/flasktools.py b/voussoirkit/flasktools.py index 1c63839..1ba5a55 100644 --- a/voussoirkit/flasktools.py +++ b/voussoirkit/flasktools.py @@ -105,6 +105,28 @@ def ensure_response_type(function): return response return wrapped +def give_theme_cookie(function, *, cookie_name, default_theme): + @functools.wraps(function) + def wrapped(*args, **kwargs): + old_theme = request.cookies.get(cookie_name, None) + new_theme = request.args.get('theme', None) + theme = new_theme or old_theme or default_theme + + request.cookies = werkzeug.datastructures.MultiDict(request.cookies) + request.cookies[cookie_name] = theme + + response = function(*args, **kwargs) + + if new_theme is None: + pass + elif new_theme == '': + response.set_cookie(cookie_name, value='', expires=0) + elif new_theme != old_theme: + response.set_cookie(cookie_name, value=new_theme, expires=2147483647) + + return response + return wrapped + def gzip_response(request, response): if response.direct_passthrough: return response