Last active
January 22, 2016 10:10
-
-
Save andretw/6881772 to your computer and use it in GitHub Desktop.
This Gist is for my post: http://www.andretw.com/2013/10/What-you-should-know-before-and-after-using-DataTables.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This Gist is for my post: http://www.andretw.com/2013/10/What-you-should-know-before-using-DataTables.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var btnActions = '<a href="#" class="btn-action glyphicons pencil btn-success _edit"><i></i></a><a href="#" class="btn-action glyphicons remove_2 btn-danger _delete"><i></i></a>'; | |
var oTable = $('#oTable').dataTable({ | |
"sDom": "<'row-fluid'<'span6'<'span3 add_new_btn'>lr><'span6'f>>t<'row-fluid'<'span6'i><'span6'p>>", | |
"bProcessing": true, | |
"bServerSide": true, | |
"sAjaxSource": "plusdiff/api", | |
"aoColumnDefs": [ | |
{ | |
"sName": "name", | |
"fnRender": function ( data, obj, full ) { | |
return obj['subObj']; | |
}, | |
"aTargets": [ 1 ] | |
}, | |
{ | |
"mData": null, | |
"fnRender": function ( oObj ) { | |
return btnActions; | |
}, | |
"aTargets": [ 5 ] | |
} | |
] | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="row-fluid"> | |
<div class="span6"> | |
<div class="span3 add_new_btn"></div> | |
<div>lENGTH CHANGING</div> | |
<div>PrOCESSING</div> | |
</div> | |
<div class="span6"> | |
<div>fILTER</div> | |
</div> | |
</div> | |
tABLE | |
<div class="row-fluid"> | |
<div class="span6"> | |
<div>iNFO</div> | |
</div> | |
<div class="span6"> | |
<div>pAGING</div> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
''' | |
Created on Sep 30, 2013 | |
@author: Andre Lee <[email protected]> | |
For connecting DataTables and Tornado. Modified from https://gist.github.com/illerucis/4586359. | |
The original version has serveral issues, but I haven't correct them all. | |
''' | |
import datetime | |
from collections import namedtuple | |
from tornado.gen import Task, Return | |
from tornado.gen import coroutine | |
# You need to initialize your own logger and mongotor | |
#get_logger | |
#get_instance | |
_logger = get_logger(__name__) | |
# translation for sorting between datatables api and mongodb | |
order_dict = {'asc': 1, 'desc': -1} | |
''' | |
Example for DataTables: | |
var oTable = $('#dt').dataTable( { | |
"sDom": "<'row-fluid'<'span6'lr><'span6'f>>t<'row-fluid'<'span6'i><'span6'p>>", | |
"bProcessing": true, | |
"bServerSide": true, | |
"sAjaxSource": "./api/"+mod_name+"/", | |
"aoColumnDefs": [ | |
{ | |
"mData": null, | |
"fnRender": function ( oObj ) { | |
return btn_actions; | |
}, | |
"aTargets": [ 5 ] | |
} | |
] | |
} ); | |
''' | |
def _filtering(request_values, columns): | |
print request_values | |
is_date = False | |
search_date = None | |
# build your filter spec | |
filters = {} | |
if ( request_values.has_key('sSearch') ) and ( request_values['sSearch'] != "" ): | |
try: | |
search_date = datetime.datetime.strptime(request_values['sSearch'], "%Y-%m-%d") | |
is_date = True | |
except Exception as e: | |
_logger.debug('search string is not a date format. %s', str(e)); | |
# the term put into search is logically concatenated with 'or' between all columns | |
or_filter_on_all_columns = [] | |
for i in range( len(columns) ): | |
column_filter = {} | |
if not is_date: | |
column_filter[columns[i]] = {'$regex': request_values['sSearch'], '$options': 'i'} | |
else: | |
#column_filter[columns[i]] = {'$gte': search_date, '$lt': search_date + datetime.timedelta(days=1)} | |
column_filter[columns[i]] = {'$gte': search_date} | |
or_filter_on_all_columns.append(column_filter) | |
filters['$or'] = or_filter_on_all_columns | |
return filters | |
def _sorting(request_values, columns): | |
order = [] | |
# mongo translation for sorting order | |
if ( request_values['iSortCol_0'] != "" ) and ( request_values['iSortingCols'] > 0 ): | |
order = {} | |
for i in range( int(request_values['iSortingCols']) ): | |
order[columns[ int(request_values['iSortCol_'+str(i)]) ]] = order_dict[request_values['sSortDir_'+str(i)]] | |
return order | |
def _paging(request_values): | |
pages = namedtuple('pages', ['start', 'length']) | |
if (request_values['iDisplayStart'] != "" ) and (request_values['iDisplayLength'] != -1 ): | |
pages.start = int(request_values['iDisplayStart']) | |
pages.length = int(request_values['iDisplayLength']) | |
return pages | |
@coroutine | |
def output_result(collection, request_values, columns, index_column): | |
query_result = yield Task(run_queries, collection, request_values, columns) | |
output = {} | |
output['sEcho'] = str(int(request_values['sEcho'])) | |
output['iTotalRecords'] = str(query_result[2]) | |
output['iTotalDisplayRecords'] = str(query_result[1]) | |
aaData_rows = [] | |
for row in query_result[0]: | |
try: | |
aaData_row = [] | |
for i in range(len(columns)): | |
target = row.get(columns[i], '') | |
if isinstance(target, unicode): | |
col = target.replace('"','\\"') | |
elif isinstance(target, str): | |
col = str(target).replace('"','\\"') | |
else: | |
col = target | |
aaData_row.append(col) | |
# add additional rows here that are not represented in the database | |
#aaData_row.append('row_'+row.get('_id', '')) | |
aaData_rows.append(aaData_row) | |
except: | |
_logger.exception('row id: %s, ', row.get('_id', '')) | |
output['aaData'] = aaData_rows | |
raise Return(output) | |
@coroutine | |
def run_queries(collection, request_values, columns): | |
# pages has 'start' and 'length' attributes | |
pages = _paging(request_values) | |
# the term you entered into the datatable search | |
filters = _filtering(request_values, columns) | |
# the document field you chose to sort | |
sorting = _sorting(request_values, columns) | |
collec = getattr(get_instance(), collection) | |
result, err = yield Task(collec.find, | |
filters, | |
skip = pages.start, | |
limit = pages.length, | |
sort = sorting) | |
result_data = result | |
cardinality_filtered = yield Task(collec.find(filters).count) | |
cardinality = yield Task(collec.find().count) | |
raise Return([result_data, cardinality_filtered, cardinality]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment