-
Notifications
You must be signed in to change notification settings - Fork 44
/
sortable.py
70 lines (55 loc) · 1.83 KB
/
sortable.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 flask_table import Table, Col, LinkCol
from flask import Flask, Markup, request, url_for
"""
A example for creating a Table that is sortable by its header
"""
app = Flask(__name__)
class SortableTable(Table):
id = Col('ID')
name = Col('Name')
description = Col('Description')
link = LinkCol(
'Link', 'flask_link', url_kwargs=dict(id='id'), allow_sort=False)
allow_sort = True
def sort_url(self, col_key, reverse=False):
if reverse:
direction = 'desc'
else:
direction = 'asc'
return url_for('index', sort=col_key, direction=direction)
@app.route('/')
def index():
sort = request.args.get('sort', 'id')
reverse = (request.args.get('direction', 'asc') == 'desc')
table = SortableTable(Item.get_sorted_by(sort, reverse),
sort_by=sort,
sort_reverse=reverse)
return table.__html__()
@app.route('/item/<int:id>')
def flask_link(id):
element = Item.get_element_by_id(id)
return '<h1>{}</h1><p>{}</p><hr><small>id: {}</small>'.format(
element.name, element.description, element.id)
class Item(object):
""" a little fake database """
def __init__(self, id, name, description):
self.id = id
self.name = name
self.description = description
@classmethod
def get_elements(cls):
return [
Item(1, 'Z', 'zzzzz'),
Item(2, 'K', 'aaaaa'),
Item(3, 'B', 'bbbbb')]
@classmethod
def get_sorted_by(cls, sort, reverse=False):
return sorted(
cls.get_elements(),
key=lambda x: getattr(x, sort),
reverse=reverse)
@classmethod
def get_element_by_id(cls, id):
return [i for i in cls.get_elements() if i.id == id][0]
if __name__ == '__main__':
app.run(debug=True)