import flask; from flask import request
import functools
import time

from voussoirkit import passwordy

import etiquette

from . import jsonify

def cached_endpoint(max_age):
    '''
    The cached_endpoint decorator can be used on slow endpoints that don't need
    to be constantly updated or endpoints that produce large, static responses.

    WARNING: The return value of the endpoint is shared with all users.
    You should never use this cache on an endpoint that provides private
    or personalized data, and you should not try to pass other headers through
    the response.

    When the function is run, its return value is stored and a random etag is
    generated so that subsequent runs can respond with 304. This way, large
    response bodies do not need to be transmitted often.

    Given a nonzero max_age, the endpoint will only be run once per max_age
    seconds on a global basis (not per-user). This way, you can prevent a slow
    function from being run very often. In-between requests will just receive
    the previous return value (still using 200 or 304 as appropriate for the
    client's provided etag).

    An example use case would be large-sized data dumps that don't need to be
    precisely up to date every time.
    '''
    state = {
        'max_age': max_age,
        'stored_value': None,
        'stored_etag': None,
        'headers': {'ETag': None, 'Cache-Control': f'max-age={max_age}'},
        'last_run': 0,
    }

    def wrapper(function):
        def get_value(*args, **kwargs):
            if state['max_age'] and (time.time() - state['last_run']) > state['max_age']:
                return state['stored_value']

            value = function(*args, **kwargs)
            if isinstance(value, flask.Response):
                if value.headers.get('Content-Type'):
                    state['headers']['Content-Type'] = value.headers.get('Content-Type')
                value = value.response

            if value != state['stored_value']:
                state['stored_value'] = value
                state['stored_etag'] = passwordy.random_hex(20)
                state['headers']['ETag'] = state['stored_etag']

            state['last_run'] = time.time()
            return value

        @functools.wraps(function)
        def wrapped(*args, **kwargs):
            value = get_value(*args, **kwargs)

            client_etag = request.headers.get('If-None-Match', None)
            if client_etag == state['stored_etag']:
                response = flask.Response(status=304, headers=state['headers'])
            else:
                response = flask.Response(value, status=200, headers=state['headers'])

            return response
        return wrapped
    return wrapper

def catch_etiquette_exception(function):
    '''
    If an EtiquetteException is raised, automatically catch it and convert it
    into a json response so that the user isn't receiving error 500.
    '''
    @functools.wraps(function)
    def wrapped(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except etiquette.exceptions.EtiquetteException as exc:
            if isinstance(exc, etiquette.exceptions.NoSuch):
                status = 404
            else:
                status = 400
            response = exc.jsonify()
            response = jsonify.make_json_response(response, status=status)
            flask.abort(response)
    return wrapped

def required_fields(fields, forbid_whitespace=False):
    '''
    Declare that the endpoint requires certain POST body fields. Without them,
    we respond with 400 and a message.

    forbid_whitespace:
        If True, then providing the field is not good enough. It must also
        contain at least some non-whitespace characters.
    '''
    def wrapper(function):
        @functools.wraps(function)
        def wrapped(*args, **kwargs):
            for requirement in fields:
                missing = (
                    requirement not in request.form or
                    (forbid_whitespace and request.form[requirement].strip() == '')
                )
                if missing:
                    response = {
                        'error_type': 'MISSING_FIELDS',
                        'error_message': 'Required fields: %s' % ', '.join(fields),
                    }
                    response = jsonify.make_json_response(response, status=400)
                    return response

            return function(*args, **kwargs)
        return wrapped
    return wrapper

@@ -63,16 +63,48 @@
 t time%0A%0A
+from voussoirkit import dotdict%0A
 from vou
@@ -1296,24 +1296,40 @@
     state = 
+dotdict.DotDict(
 %7B%0A        'm
@@ -1507,16 +1507,17 @@
 0,%0A    %7D
+)
 %0A%0A    de
@@ -1597,27 +1597,24 @@
 if state
-%5B'
+.
 max_age
-'%5D
  and (ti
@@ -1630,26 +1630,25 @@
  - state
-%5B'
+.
 last_run
 '%5D) %3E st
@@ -1639,18 +1639,16 @@
 last_run
-'%5D
 ) %3E stat
@@ -1652,19 +1652,16 @@
 tate
-%5B'
+.
 max_age
-'%5D
 :%0A  
@@ -1682,26 +1682,25 @@
 return state
-%5B'
+.
 stored_value
@@ -1699,18 +1699,16 @@
 ed_value
-'%5D
 %0A%0A      
@@ -1876,27 +1876,24 @@
    state
-%5B'
+.
 headers
-'%5D
 %5B'Conten
@@ -2002,26 +2002,25 @@
 lue != state
-%5B'
+.
 stored_value
@@ -2019,18 +2019,16 @@
 ed_value
-'%5D
 :%0A      
@@ -2038,26 +2038,25 @@
        state
-%5B'
+.
 stored_value
@@ -2055,18 +2055,16 @@
 ed_value
-'%5D
  = value
@@ -2081,26 +2081,25 @@
        state
-%5B'
+.
 stored_etag'
@@ -2097,18 +2097,16 @@
 red_etag
-'%5D
  = passw
@@ -2146,27 +2146,24 @@
    state
-%5B'
+.
 headers
-'%5D
 %5B'ETag'%5D
@@ -2166,26 +2166,25 @@
 ag'%5D = state
-%5B'
+.
 stored_etag'
@@ -2182,18 +2182,16 @@
 red_etag
-'%5D
 %0A%0A      
@@ -2205,18 +2205,17 @@
 tate
-%5B'
+.
 last_run
 '%5D =
@@ -2210,18 +2210,16 @@
 last_run
-'%5D
  = time.
@@ -2476,18 +2476,17 @@
 == state
-%5B'
+.
 stored_e
@@ -2488,18 +2488,16 @@
 red_etag
-'%5D
 :%0A      
@@ -2557,27 +2557,24 @@
 rs=state
-%5B'
+.
 headers
-'%5D
 )%0A      
@@ -2663,19 +2663,16 @@
 tate
-%5B'
+.
 headers
-'%5D
 )%0A%0A 

Use dotdict to remove all these ugly brackets.