Add decorators.give_theme_cookie to decouple from render_template.

I realized it was not appropriate for render_template to be handling
this responsibility, but previously did not think of another way.
Now I did.
This commit is contained in:
voussoir 2021-06-04 21:29:23 -07:00
parent 1554b86c11
commit 7f8a007e2d
No known key found for this signature in database
GPG key ID: 5F7554F8C26DACCB
2 changed files with 26 additions and 15 deletions

View file

@ -66,6 +66,7 @@ def decorate_and_route(*route_args, **route_kwargs):
# same one multiple times. The _fully_decorated will track that.
if not hasattr(endpoint, '_fully_decorated'):
endpoint = flasktools.ensure_response_type(endpoint)
endpoint = decorators.give_theme_cookie(endpoint)
endpoint = decorators.catch_etiquette_exception(endpoint)
endpoint = session_manager.give_token(endpoint)
@ -162,10 +163,7 @@ def back_url():
def render_template(request, template_name, **kwargs):
session = session_manager.get(request)
old_theme = request.cookies.get('etiquette_theme', None)
new_theme = request.args.get('theme', None)
theme = new_theme or old_theme or 'slate'
theme = request.cookies.get('etiquette_theme', None)
response = flask.render_template(
template_name,
@ -174,17 +172,6 @@ def render_template(request, template_name, **kwargs):
theme=theme,
**kwargs,
)
if not isinstance(response, flasktools.RESPONSE_TYPES):
response = flask.Response(response)
if new_theme is None:
pass
elif new_theme == '':
response.set_cookie('etiquette_theme', value='', expires=0)
elif new_theme != old_theme:
response.set_cookie('etiquette_theme', value=new_theme, expires=2147483647)
return response
def send_file(filepath, override_mimetype=None):

View file

@ -1,8 +1,10 @@
import flask; from flask import request
import functools
import time
import werkzeug.datastructures
from voussoirkit import dotdict
from voussoirkit import flasktools
from voussoirkit import passwordy
from voussoirkit import sentinel
@ -107,6 +109,28 @@ def catch_etiquette_exception(function):
flask.abort(response)
return wrapped
def give_theme_cookie(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
old_theme = request.cookies.get('etiquette_theme', None)
new_theme = request.args.get('theme', None)
theme = new_theme or old_theme or 'slate'
request.cookies = werkzeug.datastructures.MultiDict(request.cookies)
request.cookies['etiquette_theme'] = theme
response = function(*args, **kwargs)
if new_theme is None:
pass
elif new_theme == '':
response.set_cookie('etiquette_theme', value='', expires=0)
elif new_theme != old_theme:
response.set_cookie('etiquette_theme', value=new_theme, expires=2147483647)
return response
return wrapped
def required_fields(fields, forbid_whitespace=False):
'''
Declare that the endpoint requires certain POST body fields. Without them,