-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilters.py
70 lines (63 loc) · 2.41 KB
/
filters.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from babel.dates import format_datetime, get_timezone, format_timedelta
import pytz
from pytz import timezone
import datetime
from dateutil import parser
from base64 import b64encode
import json
def filter_to_date(input, tzname='Europe/Paris'):
"""
Parses a string into a datetime object, takes tzname as parameter.
{{ "20171212T1212" |to_date }}
"""
date = parser.parse(input)
if date.tzinfo == None :
return timezone(tzname).localize(date)
return date
def filter_datetime(value, format='date', tz='Europe/Paris', locale='fr_FR'):
"""
Pretty prints a datetime object according to parameters like format (in UTS-35 standard), tz and locale.
{{ "20171212T1212" |to_date |datetime("EEEE dd-MM-yyyy 'à' HH'h'mm", "CET", locale='es_ES') }}
"""
if format == 'date':
format="dd/MM/yyyy"
elif format == 'timeh':
format="HH'h'mm"
elif format == 'time':
format="HH:mm"
elif format == 'long_date':
format="EEEE dd MMMM yyyy"
elif format == 'daymonth':
format="dd MMMM"
return format_datetime(value, format, tzinfo=get_timezone(tz), locale=locale)
def filter_timedelta(delta, granularity='minute', threshold=2, add_direction=False , format='short', locale='fr_FR'):
"""
Pretty prints a timedelta object (difference between two datetimes).
"""
return format_timedelta(delta, granularity=granularity, threshold=threshold, add_direction=add_direction, format=format, locale=locale)
def filter_b64encode(string):
"""
Encodes an utf-8 string to base64
{{ "Alexandre" |b64encode |safe }}
"""
return b64encode(bytes(string, 'utf-8')).decode('UTF-8')
def filter_to_utf8(string):
"""
Fixes some encoding problems that can be encountered when scraping the web.
{{ "Nanterre-Université" |to_utf8 }}
"""
return string.encode('LATIN-1').decode('UTF-8')
def filter_to_json( *args, **kwargs ):
"""
Pretty prints à python object to valid JSON. Do not forget to use |safe.
Wrapper for json.dumps, see official doc.
{{ any_dict |to_json |safe }}
"""
return json.dumps( *args, **kwargs)
def filter_from_json( *args, **kwargs ):
"""
Loads a JSON string to a Python dict.
Wrapper for json.loads, see official doc.
{{ ("{\\"name\\":\\"Alexandre\\"}" |from_json).name }}
"""
return json.loads( *args, **kwargs)