-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers.py
More file actions
85 lines (71 loc) · 2.41 KB
/
helpers.py
File metadata and controls
85 lines (71 loc) · 2.41 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python
import datetime
import math
from flask import abort
from functools import wraps
# Caching
def cached(app, timeout=5 * 60, key='view/%s'):
'''http://flask.pocoo.org/docs/patterns/viewdecorators/#caching-decorator'''
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
cache_key = key % request.path
rv = app.cache.get(cache_key)
if rv is not None:
return rv
rv = f(*args, **kwargs)
app.cache.set(cache_key, rv, timeout=timeout)
return rv
return decorated_function
return decorator
# Custom Template Filters
def datetimeformat(value):
delta = datetime.datetime.now() - value
if delta.days == 0:
formatting = 'today'
elif delta.days < 10:
formatting = '{0} days ago'.format(delta.days)
elif delta.days < 28:
formatting = '{0} weeks ago'.format(int(math.ceil(delta.days/7.0)))
elif value.year == datetime.datetime.now().year:
formatting = 'on %d %b'
else:
formatting = 'on %d %b %Y'
return value.strftime(formatting)
keyspace = "fw59eorpma2nvxb07liqt83_u6kgzs41-ycdjh"
def int_str(val):
""" Turn a positive integer into a string. """
assert val >= 0
out = ""
while val > 0:
val, digit = divmod(val, len(keyspace))
out += keyspace[digit]
return out[::-1]
def str_int(val):
""" Turn a string into a positive integer. """
out = 0
for c in val:
out = out * len(keyspace) + keyspace.index(c)
return out
def chaffify(val, chaff_val = 87953):
""" Add chaff to the given positive integer. """
return val * chaff_val
def dechaffify(chaffy_val, chaff_val = 87953):
""" Dechaffs the given chaffed value. chaff_val must be the same as given to chaffify2(). If the value does not seem to be correctly chaffed, raises a ValueError. """
val, chaff = divmod(chaffy_val, chaff_val)
if chaff != 0:
raise ValueError("Invalid chaff in value")
return val
def get_or_abort(model, object_id, code=404):
"""
get an object with his given id or an abort error (404 is the default)
"""
result = model.query.get(object_id)
return result or abort(code)
def encode_id(val):
"""
Encodes ID into semi random set of strings
"""
return int_str(chaffify(val))
def decode_id(val):
return dechaffify(str_int(val))