summaryrefslogtreecommitdiff
path: root/app/utils.py
blob: 67b4897b80153c10f322d0da457b969598020ad4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from functools import wraps
from flask import request, render_template, url_for
from flask import redirect as _redirect

def _gen_tpl(endpoint):
    return endpoint.replace('.', '/') + '.jinja'

def templated(template=None):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if template is None:
                template_name = _gen_tpl(request.endpoint)
            elif template[0] == '.' and request.blueprint is not None:
                template_name = _gen_tpl(request.blueprint + template)
            else:
                template_name = template

            ctx = f(*args, **kwargs)
            if ctx is None:
                ctx = {}
            elif not isinstance(ctx, dict):
                return ctx
            return render_template(template_name, **ctx)
        return decorated_function
    return decorator

def redirect (target, **kwargs):
    code = kwargs.pop("_code", None)
    url = url_for(target, **kwargs)

    if code is None:
        return _redirect(url)
    else:
        return _redirect(url, code)