-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverside_table.py
82 lines (67 loc) · 2.13 KB
/
serverside_table.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
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True)
age = db.Column(db.Integer, index=True)
address = db.Column(db.String(256))
phone = db.Column(db.String(20))
email = db.Column(db.String(120))
def to_dict(self):
return {
'name': self.name,
'age': self.age,
'address': self.address,
'phone': self.phone,
'email': self.email
}
db.create_all()
@app.route('/')
def index():
return render_template('server_table.html', title='Server-Driven Table')
@app.route('/api/data')
def data():
query = User.query
# search filter
search = request.args.get('search[value]')
if search:
query = query.filter(db.or_(
User.name.like(f'%{search}%'),
User.email.like(f'%{search}%')
))
total_filtered = query.count()
# sorting
order = []
i = 0
while True:
col_index = request.args.get(f'order[{i}][column]')
if col_index is None:
break
col_name = request.args.get(f'columns[{col_index}][data]')
if col_name not in ['name', 'age', 'email']:
col_name = 'name'
descending = request.args.get(f'order[{i}][dir]') == 'desc'
col = getattr(User, col_name)
if descending:
col = col.desc()
order.append(col)
i += 1
if order:
query = query.order_by(*order)
# pagination
start = request.args.get('start', type=int)
length = request.args.get('length', type=int)
query = query.offset(start).limit(length)
# response
return {
'data': [user.to_dict() for user in query],
'recordsFiltered': total_filtered,
'recordsTotal': User.query.count(),
'draw': request.args.get('draw', type=int),
}
if __name__ == '__main__':
app.run()