/
template.py
186 lines (156 loc) · 5.47 KB
/
template.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import re
import functools
try:
from urllib.parse import quote
except ImportError:
# Python 2
from urllib import quote
__all__ = ['expand']
patterns = re.compile("{([^\}]+)}")
def expand(template, variables=None):
"""
Expand a URL template string using the passed variables
"""
if variables is None:
variables = {}
return patterns.sub(functools.partial(_replace, variables), template)
# Utils
def _flatten(container):
"""
_flatten a sequence of sequences into a single list
"""
_flattened = []
for sequence in container:
_flattened.extend(sequence)
return _flattened
# Format functions
# ----------------
# These are responsible for formatting the (key, value) pair into a string
def _format_pair_no_equals(explode, separator, escape, key, value):
"""
Format a key, value pair but don't include the equals sign
when there is no value
"""
if not value:
return key
return _format_pair(explode, separator, escape, key, value)
def _format_pair_with_equals(explode, separator, escape, key, value):
"""
Format a key, value pair including the equals sign
when there is no value
"""
if not value:
return key + '='
return _format_pair(explode, separator, escape, key, value)
def _format_pair(explode, separator, escape, key, value):
if isinstance(value, (list, tuple)):
join_char = ","
if explode:
join_char = separator
try:
dict(value)
except:
# Scalar container
if explode:
items = ["%s=%s" % (key, escape(v)) for v in value]
return join_char.join(items)
else:
escaped_value = join_char.join(map(escape, value))
else:
# Tuple container
if explode:
items = ["%s=%s" % (k, escape(v)) for (k,v) in value]
return join_char.join(items)
else:
items = _flatten(value)
escaped_value = join_char.join(map(escape, items))
else:
escaped_value = escape(value)
return '%s=%s' % (key, escaped_value)
def _format_default(explode, separator, escape, key, value):
if isinstance(value, (list, tuple)):
join_char = ","
if explode:
join_char = separator
try:
dict(value)
except:
# Scalar container
escaped_value = join_char.join(map(escape, value))
else:
# Tuple container
if explode:
items = ["%s=%s" % (k, escape(v)) for (k,v) in value]
escaped_value = join_char.join(items)
else:
items = _flatten(value)
escaped_value = join_char.join(map(escape, items))
else:
escaped_value = escape(value)
return escaped_value
# Modifer functions
# -----------------
# These are responsible for modifying the variable before formatting
_identity = lambda x: x
def _truncate(string, num_chars):
return string[:num_chars]
# Splitting functions
# -------------------
# These are responsible for splitting a string into a sequence of (key,
# modifier) tuples
def _split_basic(string):
"""
Split a string into a list of tuples of the form
(key, modifier_fn, explode) where modifier_fn is a function that applies the
appropriate modification to the variable.
"""
tuples = []
for word in string.split(','):
# Attempt to split on colon
parts = word.split(':', 2)
key, modifier_fn, explode = parts[0], _identity, False
if len(parts) > 1:
modifier_fn = functools.partial(
_truncate, num_chars=int(parts[1]))
if word[len(word) - 1] == '*':
key = word[:len(word) - 1]
explode = True
tuples.append((key, modifier_fn, explode))
return tuples
def _split_operator(string):
return _split_basic(string[1:])
# Escaping functions
# ------------------
def _escape_all(value):
return quote(str(value), safe="")
def _escape_reserved(value):
return quote(str(value), safe="/!,.;")
# Operator map
# ------------
# A mapping of:
# operator -> (prefix, separator, split_fn, escape_fn, format_fn)
operator_map = {
'+': ('', ',', _split_operator, _escape_reserved, _format_default),
'#': ('#', ',', _split_operator, _escape_reserved, _format_default),
'.': ('.', '.', _split_operator, _escape_all, _format_default),
'/': ('/', '/', _split_operator, _escape_all, _format_default),
';': (';', ';', _split_operator, _escape_all, _format_pair_no_equals),
'?': ('?', '&', _split_operator, _escape_all, _format_pair_with_equals),
'&': ('&', '&', _split_operator, _escape_all, _format_pair_with_equals),
}
defaults = ('', ',', _split_basic, _escape_all, _format_default)
def _replace(variables, match):
"""
Return the appropriate replacement for `match` using the passed variables
"""
expression = match.group(1)
# Look-up chars and functions for the specified operator
prefix_char, separator_char, split_fn, escape_fn, format_fn = operator_map.get(
expression[0], defaults)
replacements = []
for key, modify_fn, explode in split_fn(expression):
if key in variables:
variable = modify_fn(variables[key])
replacement = format_fn(explode, separator_char, escape_fn, key, variable)
replacements.append(replacement)
return prefix_char + separator_char.join(replacements)