让DataTables支持Flask

编写于

近来工作原因,正在从Django转到Flask,而其中将DataTables移植到了Flask中去.

基本的功能还是工作了,还差那个正则和另外一个不常用到的属性,现在还是用着先,如果有任何BUG请留言或者给我发邮件.

需要用到常用扩展:Flask-Sqlalchemy,Flask-WTF

    dt = DataTable()
dt.filter(Account.all_username_q(),(
(‘AccountAttribute.id’,‘ID’),
(‘AccountAttribute.username’,Account.display_name(‘username’)),
(‘AccountAttribute.value’,Account.display_name(‘CT.LanNumber’)),
))
return dt.json()

一下是详细代码,英文不好,见到错误请多多指正:
# coding:utf-8

from flask.ext.wtf import Form,html5,
TextField,StringField,IntegerField,BooleanField
from flask import request,jsonify

from core import db

class DataTableForm(Form):
iDisplayStart = IntegerField()
iDisplayLength = IntegerField()
iColumns = IntegerField()
sSearch = StringField(64)
bRegex = BooleanField()
sEcho = StringField(64)

class DataTable(object):
“’
dt = DataTable()
dt.filter(Account.all_username_q(),(
(‘AccountAttribute.id’,‘ID’),
(‘AccountAttribute.username’,Account.display_name(‘username’)),
(‘AccountAttribute.value’,Account.display_name(‘CT.LanNumber’)),
))
return dt.json()
“’

form = None
data = None

def valid(self):
self.form = DataTableForm(csrf_enabled=False)
return self.form.validate_on_submit()

def col(self,name):
table,field = name.split(‘.’)
for col_desc in self.query.column_descriptions:
if col_desc[‘name’] == table:
return getattr(col_desc[‘type’],field)

elif col_desc[‘name’] == field:
return col_desc[‘expr’]

def filter(self,query,columns):
if self.valid():
# total columns working
col_range = range(0,int(request.form[‘iColumns’]))

# search key
# TODO support regex
key = self.form.data[‘sSearch’]
self.query = query
self.columns = columns
self.total = query.count()

# search columns
q_sort = ()
q_filter = ()
q_cols = ()
for i in colrange:
# search it
# TODO supported regex
#print request.form.get(‘bRegex
%d’ %i,None)
search_col = self.col(columns[i][0])
q_cols += (search_col,)
if search_col:
searchable = True if request.form.get(‘bSearchable%d’ %i,None) == ‘true’ else False
if search_able:
# change search column type to text
search_col = db.func.text(search_col)

searchkey = request.form.get(‘sSearch%d’ %i,None)
if search_key:
q_filter += (search_col.contains(search_key),)
else:
q_filter += (search_col.contains(key),)

# sort it
sortkey = int(request.form.get(‘iSortCol%d’ %i,-1))
if sort_key > -1:
sortdir = unicode(request.form.get(‘sSortDir%d’ %i,“))
sort_name = columns[sort_key][0]
q_sort += (getattr(db,sort_dir,‘asc’)(self.col(sortname)),)

# unkown row
#print request.form.get(‘mDataProp
%d’ %i,None)

if qfilter:
query = query.filter(db.or
(*q_filter))
if q_sort:
query = query.order_by(*q_sort)

self.cols = q_cols

# limit max 100
start = self.form.data[‘iDisplayStart’]
stop = start + min(self.form.data[‘iDisplayLength’],100)

# reset it to new query
self.total_filtered = query.count()
self.new_query = query.slice(start,stop)

def json(self):
data = {
‘iTotalRecords’: self.total,
‘iTotalDisplayRecords’: self.total_filtered,
‘sEcho’: self.form.data[‘sEcho’],
‘sColumns’: [col[1] for col in self.columns],
‘aaData’: list(self.new_query.values(*self.cols)),
}
return jsonify(data)