/
columns.py
311 lines (239 loc) · 9.22 KB
/
columns.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
from __future__ import unicode_literals
from flask import Markup, url_for
from babel.dates import format_date, format_datetime
from flask.ext.babel import gettext as _
from .html import element
def _single_get(item, key):
# First, try to lookup the key as if the item were a dict. If
# that fails, lookup the key as an atrribute of an item.
try:
val = item[key]
except (KeyError, TypeError):
val = getattr(item, key)
# once we have the value, try calling it as a function. If
# that fails, the just return it.
try:
return val()
except TypeError:
return val
def _recursive_getattr(item, keys):
# See if keys is as string, if so, we need to split on the dots.
try:
keys = keys.split('.')
except AttributeError:
pass
if item is None:
return None
if len(keys) == 1:
return _single_get(item, keys[0])
else:
return _recursive_getattr(_single_get(item, keys[0]), keys[1:])
class Col(object):
"""The subclass for all Columns, and the class that just gets some
data from each item an outputs it.
We use this hack with _counter to make sure that the columns end
up in the same order as when declared. Each column must set a
name, which is used in as the heading for that column, and can
optionally set an attr or an attr_list. attr='foo' is equivalent
to attr_list=['foo'] and attr_list=['foo', 'bar', 'baz'] will
attempt to get item.foo.bar.baz for each item in the iterable
given to the table. If item.foo.bar is None, then this process
will terminate and will not error. However, if item.foo.bar is an
object without an attribute 'baz', then this will currently error.
"""
_counter = 0
def __init__(self, name, attr=None, attr_list=None,
allow_sort=True, show=True):
self.name = name
self.allow_sort = allow_sort
self._counter_val = Col._counter
self.attr_list = attr_list
if attr:
self.attr_list = attr.split('.')
self.show = show
Col._counter += 1
def get_attr_list(self, attr):
if self.attr_list:
return self.attr_list
elif attr:
return attr.split('.')
else:
return None
def from_attr_list(self, item, attr_list):
out = _recursive_getattr(item, attr_list)
if out is None:
return ''
else:
return out
def td(self, item, attr):
content = self.td_contents(item, self.get_attr_list(attr))
return element('td', content=content, escape_content=False)
def td_contents(self, item, attr_list):
"""Given an item and an attr, return the contents of the td.
This method is a likely candidate to override when extending
the Col class, which is done in LinkCol and
ButtonCol. Override this method if you need to get some extra
data from the item.
Note that the output of this function is NOT escaped.
"""
return self.td_format(self.from_attr_list(item, attr_list))
def td_format(self, content):
"""Given just the value extracted from the item, return what should
appear within the td.
This method is also a good choice to override when extending,
which is done in the BoolCol, DateCol and DatetimeCol
classes. Override this method when you just need the standard
data that attr_list gets from the item, but need to adjust how
it is represented.
Note that the output of this function is escaped.
"""
return Markup.escape(content)
class OptCol(Col):
"""Translate the contents according to a dictionary of choices.
"""
def __init__(self, name, choices=None, default_key=None, default_value='',
coerce_fn=None, **kwargs):
super(OptCol, self).__init__(name, **kwargs)
if choices is None:
self.choices = {}
else:
self.choices = choices
self.default_value = self.choices.get(default_key, default_value)
self.coerce_fn = coerce_fn
def coerce_content(self, content):
if self.coerce_fn:
return self.coerce_fn(content)
else:
return content
def td_format(self, content):
return self.choices.get(
self.coerce_content(content), self.default_value)
class BoolCol(OptCol):
"""Output Yes/No values for truthy or falsey values.
"""
def __init__(self, name, **kwargs):
super(BoolCol, self).__init__(
name,
choices={True: _('Yes'), False: _('No')},
coerce_fn=bool,
**kwargs)
class DateCol(Col):
"""Format the content as a date, unless it is None, in which case,
output empty.
"""
def __init__(self, name, date_format='short', **kwargs):
super(DateCol, self).__init__(name, **kwargs)
self.date_format = date_format
def td_format(self, content):
if content:
return format_date(content, self.date_format)
else:
return ''
class DatetimeCol(Col):
"""Format the content as a datetime, unless it is None, in which case,
output empty.
"""
def __init__(self, name, datetime_format='short', **kwargs):
super(DatetimeCol, self).__init__(name, **kwargs)
self.datetime_format = datetime_format
def td_format(self, content):
if content:
return format_datetime(content, self.datetime_format)
else:
return ''
class LinkCol(Col):
"""Format the content as a link. Requires a endpoint to use to find
the url and can also take a dict of url_kwargs which is expected
to have values that are strings which are used to get data from
the item.
Eg:
view = LinkCol('View', 'view_fn', url_kwargs=dict(id='id'))
This will create a link to the address given by url_for('view_fn',
id=item.id) for each item in the iterable.
"""
def __init__(self, name, endpoint, attr=None, attr_list=None,
url_kwargs=None, url_kwargs_extra=None, **kwargs):
super(LinkCol, self).__init__(
name,
attr=attr,
attr_list=attr_list,
**kwargs)
self.endpoint = endpoint
self._url_kwargs = url_kwargs or {}
self._url_kwargs_extra = url_kwargs_extra or {}
def url_kwargs(self, item):
# We give preference to the item kwargs, rather than the extra
# kwargs.
kwargs = self._url_kwargs_extra.copy()
item_kwargs = {k: _recursive_getattr(item, v)
for k, v in self._url_kwargs.items()}
kwargs.update(item_kwargs)
return kwargs
def get_attr_list(self, attr):
return super(LinkCol, self).get_attr_list(None)
def text(self, item, attr_list):
if attr_list:
return self.from_attr_list(item, attr_list)
else:
return self.name
def url(self, item):
return url_for(self.endpoint, **self.url_kwargs(item))
def td_contents(self, item, attr_list):
attrs = dict(href=self.url(item))
text = self.td_format(self.text(item, attr_list))
return element('a', attrs=attrs, content=text, escape_content=False)
class ButtonCol(LinkCol):
"""Just the same a LinkCol, but creates an empty form which gets
posted to the specified url.
Eg:
delete = ButtonCol('Delete', 'delete_fn', url_kwargs=dict(id='id'))
When clicked, this will post to url_for('delete_fn', id=item.id).
Can pass button_attrs to pass extra attributes to the button
element.
"""
def __init__(self, name, endpoint, attr=None, attr_list=None,
url_kwargs=None, button_attrs=None, **kwargs):
super(ButtonCol, self).__init__(
name,
endpoint,
attr=attr,
attr_list=attr_list,
url_kwargs=url_kwargs, **kwargs)
self.button_attrs = button_attrs or {}
def td_contents(self, item, attr_list):
button_attrs = dict(self.button_attrs)
button_attrs['type'] = 'submit'
button = element(
'button',
attrs=button_attrs,
content=self.text(item, attr_list),
)
return element(
'form',
attrs=dict(
method='post',
action=self.url(item),
),
content=button,
escape_content=False,
)
class NestedTableCol(Col):
"""This column type allows for nesting tables into a column. The
nested table is defined as a sub-class of Table as usual. Then in
the main table, a column is defined using NestedTableCol with the
second argument being the name of the Table sub-class object
defined for the nested table.
Eg:
class MySubTable(Table):
a = Col('1st nested table col')
b = Col('2nd nested table col')
class MainTable(Table):
id = Col('id')
objects = NestedTableCol('objects', MySubTable)
"""
def __init__(self, name, table_class, **kwargs):
super(NestedTableCol, self).__init__(name, **kwargs)
self.table_class = table_class
def td_format(self, content):
t = self.table_class(content).__html__()
return t