Skip to content

Commit

Permalink
Some code cleanup, PEP8 updates, updated requirements.
Browse files Browse the repository at this point in the history
git-svn-id: https://projects.ninemoreminutes.com/svn/django-datatables/trunk@42 d7121a62-6ae3-45d9-917d-ff5cd7ed6f65
  • Loading branch information
chris authored and cchurch committed Aug 30, 2014
1 parent 9cf07a8 commit 8443805
Show file tree
Hide file tree
Showing 12 changed files with 188 additions and 75 deletions.
1 change: 1 addition & 0 deletions datatables/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
__version__ = '0.2a0'

from columns import *
from datatable import *
from decorators import *
Expand Down
25 changes: 17 additions & 8 deletions datatables/columns.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
# Python
from copy import deepcopy
import logging

# Django
from django.utils.copycompat import deepcopy
from django.utils.safestring import mark_safe
from django.forms.widgets import media_property
from django.template import Context
from django.template.loader import select_template

# Django-DataTables
from utils import hungarian_to_python, lookupattr
from .utils import hungarian_to_python, lookupattr

__all__ = ['Column', 'CheckboxColumn', 'SimpleCheckboxColumn',
'ExpandableColumn']

__all__ = ['Column', 'CheckboxColumn', 'SimpleCheckboxColumn', 'ExpandableColumn']
logger = logging.getLogger('datatables.columns')


class ColumnMeta(type):
Expand Down Expand Up @@ -46,8 +52,8 @@ def __init__(self, **kwargs):
try:
self.options[key] = hungarian_to_python(key, value)
kwargs.pop(key)
except NameError:
pass
except NameError, e:
logger.warning('Invalid Column argument: %r=%r', key, value)
for key, value in self.DEFAULTS.items():
setattr(self, key, kwargs.get(key, value))
self.classes = set(self.classes or [])
Expand All @@ -68,7 +74,7 @@ class Media:

def __init__(self, **kwargs):
kwargs.setdefault('bSortable', False)
self.name = kwargs.get('name', None)
self.name = kwargs.pop('name', None)
super(CheckboxColumn, self).__init__(**kwargs)
self.classes.add('datatables_checkbox_column')
self.template = select_template(['datatables/checkbox_column.html'])
Expand All @@ -79,7 +85,6 @@ def render_label(self, bc):
'name': self.name or bc.name,
'value': '__ALL__',
})
#return mark_safe(self.template.render(c))
return mark_safe(
select_template(
['datatables/checkbox_column_label.html']
Expand All @@ -96,11 +101,15 @@ def render_value(self, row, bc):
})
return mark_safe(self.template.render(c))


class SimpleCheckboxColumn(Column):

def render_value(self, row, bc):
checked = bool(bc.model_field and lookupattr(row, bc.model_field))
return mark_safe('<input type="checkbox" value="%s" %s>' % (getattr(row, 'id', ''), 'checked' if checked else ''))
value = '<input type="checkbox" value="%s" %s>' % \
(getattr(row, 'id', ''), 'checked' if checked else '')
return mark_safe(value)


class ExpandableColumn(Column):

Expand Down
16 changes: 8 additions & 8 deletions datatables/datatable.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Python
from copy import deepcopy

# Django
from django.http import HttpResponse
from django.template import Context
from django.template.loader import select_template
from django.utils.copycompat import deepcopy
from django.utils.datastructures import SortedDict
from django.utils.safestring import mark_safe
from django.db.models import Q
Expand Down Expand Up @@ -147,25 +149,23 @@ def rows(self):

def js_options(self):
options = deepcopy(self._meta.options)
columns = self.bound_columns
aoColumnDefs = options.setdefault('aoColumnDefs', [])
colopts = SortedDict()
for index, name in enumerate(columns.keys()):
column = columns[name]
for key, value in column.options.items():
for index, bcol in enumerate(self.bound_columns.values()):
for key, value in bcol.options.items():
if not (key, str(value)) in colopts.keys():
colopts[(key, str(value))] = {}
colopts[(key, str(value))]['targets'] = []
coltargets = colopts[(key, str(value))]['targets'] + [index]
colopts[(key, str(value))]['targets'] = coltargets
colopts[(key, str(value))]['key'] = key
colopts[(key, str(value))]['value'] = value
if column.sort_field not in columns:
if bcol.sort_field not in self.bound_columns:
continue
if column.sort_field == column.display_field:
if bcol.sort_field == bcol.display_field:
continue
key = 'iDataSort'
value = columns.keys().index(column.sort_field)
value = self.bound_columns.keys().index(bcol.sort_field)
if not (key, str(value)) in colopts.keys():
colopts[(key, str(value))] = {}
colopts[(key, str(value))]['targets'] = []
Expand Down
21 changes: 11 additions & 10 deletions datatables/utils.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
# Python
from copy import deepcopy

# Django
from django.utils.copycompat import deepcopy
from django.utils import simplejson
try:
import json
except ImportError:
from django.utils import simplejson as json

__all__ = ['hungarian_to_python', 'lookupattr']


def dumpjs(obj, *args, **kwargs):
"""Dump a Python object as Javascript, with support for __json__ method."""
class Encoder(simplejson.JSONEncoder):
class Encoder(json.JSONEncoder):
def iterencode(self, o, _one_shot=False):
#print o
if hasattr(o, '__json__'):
if callable(o.__json__):
print 'foo', o
return o.__json__()
else:
return o.__json__
else:
return super(Encoder, self).iterencode(o)
#, _one_shot=_one_shot)
kwargs['cls'] = Encoder
kwargs['sort_keys'] = True
#return simplejson.dumps(obj, *args, **kwargs)
output = simplejson.dumps(obj, *args, **kwargs)
output = json.dumps(obj, *args, **kwargs)
for key, val in obj.items():
if 'fn' == key[0:2]:
output = output.replace(simplejson.dumps(val), val)
# FIXME: Kind of a hack.
output = output.replace(json.dumps(val), val)
return output


Expand All @@ -49,7 +51,6 @@ def __json__(self):

def __deepcopy__(self, memo):
return deepcopy(self.fndef, memo)
#return self.__class__(deepcopy(self.fndef, memo))


def hungarian_to_python(name, value):
Expand Down
40 changes: 23 additions & 17 deletions requirements/dev.txt
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
# MacOS with Python 2.6.6 from python.org may need to use tox==1.4.2 with
# PIP Requirements File (for a development/build environment)
# virtualenv==1.8.2 and pip==1.2.1 instead.
argparse==1.2.1
coverage==3.6
coverage==3.7
decorator==3.4.0
distribute==0.6.36
Django==1.5.1
django-debug-toolbar==0.9.4
django-devserver==0.6.2
django-extensions==1.1.1
django-fortunecookie==0.1.3
https://github.com/gregmuellegger/django-setuptest/tarball/master#egg=django-setuptest
django-sortedm2m==0.5.0
docutils==0.10
Jinja2==2.6
pep8==1.4.5
py==1.4.13
distribute==0.7.3
django-debug-toolbar==0.11.0
django-devserver==0.7.0
django-extensions==1.2.5
django-fortunecookie==0.1.5
django-setuptest==0.1.4
django-sortedm2m==0.6.0
Django==1.5.5
docutils==0.11
Jinja2==2.7.1
MarkupSafe==0.18
pep8==1.4.6
pip-tools==0.3.4
py==1.4.18
Pygments==1.6
Sphinx==1.2b1
South==0.7.6
tox==1.4.3
virtualenv==1.9.1
six==1.4.1
South==0.8.4
Sphinx==1.2b3
sqlparse==0.1.10
tox==1.6.1
virtualenv==1.10.1
22 changes: 11 additions & 11 deletions requirements/test.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# PIP Requirements File (for automated testing with Tox, excludes Django)
argparse
coverage
decorator
distribute
django-debug-toolbar
django-devserver
django-extensions
django-fortunecookie>=0.1.1
https://github.com/gregmuellegger/django-setuptest/tarball/master#egg=django-setuptest
django-sortedm2m
South
argparse==1.2.1
coverage==3.7
decorator==3.4.0
distribute==0.7.3
django-debug-toolbar==0.11.0
django-devserver==0.7.0
django-extensions==1.2.5
django-fortunecookie==0.1.5
django-setuptest==0.1.4
django-sortedm2m==0.6.0
South==0.8.4
5 changes: 4 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ def tags(self):
return version

def get_svn_revision(self):
revision = _egg_info.get_svn_revision(self)
try:
revision = _egg_info.get_svn_revision(self)
except TypeError:
revision = _egg_info.get_svn_revision()
if revision == '0':
path = os.path.dirname(__file__)
try:
Expand Down
22 changes: 16 additions & 6 deletions test_app/tests.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Python
import imp
try:
import json
except ImportError:
from django.utils import simplejson as json
import sys

# Django
from django.test import TestCase
Expand All @@ -21,6 +23,14 @@ class TestDataTables(TestCase):

fixtures = ['fortunecookies']

def setUp(self):
super(TestDataTables, self).setUp()
# For test coverage.
imp.reload(sys.modules['datatables.columns'])
#imp.reload(sys.modules['datatables.datatable'])
imp.reload(sys.modules['datatables.decorators'])
imp.reload(sys.modules['datatables.utils'])

def test_hungarian_to_python(self):
fndef = 'function(oSettings, json) { alert("Init Complete!"); }'
result = datatables.hungarian_to_python('fnInitComplete', fndef)
Expand Down Expand Up @@ -367,24 +377,24 @@ def test_server_side(self):
args['bRegex'] = False
response = self.client.get('/', args)
data = json.loads(response.content)
count = FortuneCookie.objects.filter(fortune__icontains=args['sSearch']).count()
self.assertTrue(count == len(data['aaData']))
qs = FortuneCookie.objects.filter(fortune__icontains=args['sSearch'])
self.assertTrue(qs.count() == len(data['aaData']))
del args['sSearch']
args['sSearch_0'] = 'you'
args['bRegex_0'] = False
response = self.client.get('/', args)
data = json.loads(response.content)
self.assertTrue(count == len(data['aaData']))
self.assertTrue(qs.count() == len(data['aaData']))
args['sSearch_0'] = '^You.*$'
args['bRegex_0'] = True
count = FortuneCookie.objects.filter(fortune__regex=args['sSearch_0']).count()
qs = FortuneCookie.objects.filter(fortune__regex=args['sSearch_0'])
response = self.client.get('/', args)
data = json.loads(response.content)
self.assertTrue(count == len(data['aaData']))
self.assertTrue(qs.count() == len(data['aaData']))
del args['sSearch_0']
del args['bRegex_0']
args['sSearch'] = '^You.*$'
args['bRegex'] = True
response = self.client.get('/', args)
data = json.loads(response.content)
self.assertTrue(count == len(data['aaData']))
self.assertTrue(qs.count() == len(data['aaData']))
1 change: 1 addition & 0 deletions test_app/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# Django
from django.conf.urls import patterns, include, url

urlpatterns = patterns('test_app.views', *[
Expand Down
4 changes: 2 additions & 2 deletions test_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ class Meta:
aLengthMenu = [[3, 10, 25, 50, -1], [3, 10, 25, 50, "All"]]
#fnInitComplete = '''function(oSettings, json) {
# alert("Init Complete!"); }'
bServerSide = True
sAjaxSource = '/'
#bServerSide = True
#sAjaxSource = '/'
#fnServerData = '''function( sUrl, aoData, fnCallback ) {
# $.ajax( {
# "url": sUrl,
Expand Down
6 changes: 3 additions & 3 deletions test_project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
STATIC_URL = '/static/'

MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
#'debug_toolbar.middleware.DebugToolbarMiddleware',
'devserver.middleware.DevServerMiddleware',
)

Expand All @@ -43,11 +43,11 @@
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
#'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'debug_toolbar',
#'debug_toolbar',
'devserver',
'django_extensions',
'south',
Expand Down
Loading

0 comments on commit 8443805

Please sign in to comment.