Passed
Push — master ( b26c53...97b1b2 )
by Jochen
02:16
created

byceps.util.templatefilters._get_timezone()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
"""
2
byceps.util.templatefilters
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
Provide and register custom template filters.
6
7
:Copyright: 2006-2019 Jochen Kupperschmidt
8
:License: Modified BSD, see LICENSE for details.
9
"""
10
11
from datetime import datetime
12
13
from flask import current_app
14
from jinja2 import evalcontextfilter, Markup
15
from jinja2.filters import do_default, do_trim
16
from pytz import timezone, UTC
17
18
from .datetime import format as dateformat
19
from . import money
20
21
22
@evalcontextfilter
23
def dim(eval_ctx, value):
24
    """Render value in a way so that it looks dimmed."""
25
    dimmed = _dim(value)
26
    return _wrap_markup_on_autoescape(eval_ctx, dimmed)
27
28
29
def _dim(value):
30
    return f'<span class="dimmed">{value}</span>'
31
32
33
@evalcontextfilter
34
def fallback(eval_ctx, value, fallback='nicht angegeben'):
35
    defaulted = do_trim(do_default(value, '', True))
36
    result = value if defaulted else _dim(fallback)
37
    return _wrap_markup_on_autoescape(eval_ctx, result)
38
39
40
def _wrap_markup_on_autoescape(eval_ctx, value):
41
    return Markup(value) if eval_ctx.autoescape else value
42
43
44
def separate_thousands(number: int) -> str:
45
    """Insert locale-specific characters to separate thousands."""
46
    return f'{number:n}'
47
48
49
def local_tz_to_utc(dt: datetime):
50
    return (_get_timezone()
51
        .localize(dt)
52
        .astimezone(UTC)
53
        # Keep SQLAlchemy from converting it to another zone.
54
        .replace(tzinfo=None))
55
56
57
def utc_to_local_tz(dt: datetime) -> datetime:
58
    """Convert naive date/time object from UTC to configured time zone."""
59
    tz = _get_timezone()
60
    return UTC.localize(dt).astimezone(tz)
61
62
63
def _get_timezone():
64
    return timezone(current_app.config['TIMEZONE'])
65
66
67
def register(app):
68
    """Make functions available as template filters."""
69
    functions = [
70
        dateformat.format_custom,
71
        dateformat.format_date_iso,
72
        dateformat.format_date_short,
73
        dateformat.format_date_long,
74
        dateformat.format_datetime_iso,
75
        dateformat.format_datetime_short,
76
        dateformat.format_datetime_long,
77
        dateformat.format_time,
78
        dim,
79
        fallback,
80
        money.format_euro_amount,
81
        separate_thousands,
82
        utc_to_local_tz,
83
    ]
84
85
    for f in functions:
86
        app.add_template_filter(f)
87