Skip to content

Commit

Permalink
added flake8 to travis ci
Browse files Browse the repository at this point in the history
because style matters ;)
  • Loading branch information
trbs committed Nov 20, 2012
1 parent f2dd162 commit a39e554
Showing 56 changed files with 406 additions and 422 deletions.
6 changes: 4 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -9,7 +9,9 @@ env:
- DJANGO_VERSION=1.3.1

install:
- pip install --use-mirrors -q Django==$DJANGO_VERSION PyYAML unittest2
- pip install --use-mirrors -q Django==$DJANGO_VERSION PyYAML unittest2 flake8
- python setup.py -q install

script: python setup.py test
script:
- flake8 .
- python setup.py test
22 changes: 8 additions & 14 deletions django_extensions/admin/__init__.py
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@
from django.utils.text import get_text_list
try:
from functools import update_wrapper
assert update_wrapper
except ImportError:
from django.utils.functional import update_wrapper

@@ -27,6 +28,7 @@

if 'reversion' in settings.INSTALLED_APPS:
from reversion.admin import VersionAdmin as ModelAdmin
assert ModelAdmin
else:
from django.contrib.admin import ModelAdmin

@@ -63,11 +65,8 @@ def wrapper(*args, **kwargs):

info = self.model._meta.app_label, self.model._meta.module_name

urlpatterns = patterns('',
url(r'foreignkey_autocomplete/$',
wrap(self.foreignkey_autocomplete),
name='%s_%s_autocomplete' % info),
) + super(ForeignKeyAutocompleteAdmin, self).get_urls()
urlpatterns = patterns('', url(r'foreignkey_autocomplete/$', wrap(self.foreignkey_autocomplete), name='%s_%s_autocomplete' % info))
urlpatterns += super(ForeignKeyAutocompleteAdmin, self).get_urls()
return urlpatterns

def foreignkey_autocomplete(self, request):
@@ -100,9 +99,7 @@ def construct_search(field_name):
data = ''
if query:
for bit in query.split():
or_queries = [models.Q(**{construct_search(
smart_str(field_name)): smart_str(bit)})
for field_name in search_fields.split(',')]
or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')]
other_qs = QuerySet(model)
other_qs.dup_select_related(queryset)
other_qs = other_qs.filter(reduce(operator.or_, or_queries))
@@ -134,14 +131,11 @@ def formfield_for_dbfield(self, db_field, **kwargs):
Overrides the default widget for Foreignkey fields if they are
specified in the related_search_fields class attribute.
"""
if (isinstance(db_field, models.ForeignKey) and
db_field.name in self.related_search_fields):
if (isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields):
model_name = db_field.rel.to._meta.object_name
help_text = self.get_help_text(db_field.name, model_name)
if kwargs.get('help_text'):
help_text = u'%s %s' % (kwargs['help_text'], help_text)
kwargs['widget'] = ForeignKeySearchInput(db_field.rel,
self.related_search_fields[db_field.name])
kwargs['widget'] = ForeignKeySearchInput(db_field.rel, self.related_search_fields[db_field.name])
kwargs['help_text'] = help_text
return super(ForeignKeyAutocompleteAdmin,
self).formfield_for_dbfield(db_field, **kwargs)
return super(ForeignKeyAutocompleteAdmin, self).formfield_for_dbfield(db_field, **kwargs)
2 changes: 1 addition & 1 deletion django_extensions/admin/widgets.py
Original file line number Diff line number Diff line change
@@ -78,7 +78,7 @@ def render(self, name, value, attrs=None):
'app_label': app_label,
'label': label,
'name': name,
'pre_django_14': (django.VERSION[:2]<(1,4)),
'pre_django_14': (django.VERSION[:2] < (1, 4)),
}
output.append(render_to_string(self.widget_template or (
'django_extensions/widgets/%s/%s/foreignkey_searchinput.html' % (app_label, model_name),
10 changes: 6 additions & 4 deletions django_extensions/db/fields/__init__.py
Original file line number Diff line number Diff line change
@@ -8,11 +8,13 @@

try:
import uuid
assert uuid
except ImportError:
from django_extensions.utils import uuid

try:
from django.utils.timezone import now as datetime_now
assert datetime_now
except ImportError:
import datetime
datetime_now = datetime.datetime.now
@@ -232,9 +234,9 @@ def get_internal_type(self):

def contribute_to_class(self, cls, name):
if self.primary_key:
assert not cls._meta.has_auto_field, \
"A model can't have more than one AutoField: %s %s %s; have %s" % \
(self, cls, name, cls._meta.auto_field)
assert not cls._meta.has_auto_field, "A model can't have more than one AutoField: %s %s %s; have %s" % (
self, cls, name, cls._meta.auto_field
)
super(UUIDField, self).contribute_to_class(cls, name)
cls._meta.has_auto_field = True
cls._meta.auto_field = self
@@ -266,7 +268,7 @@ def pre_save(self, model_instance, add):
value = unicode(self.create_uuid())
setattr(model_instance, self.attname, value)
return value

def formfield(self, **kwargs):
if self.auto:
return None
17 changes: 10 additions & 7 deletions django_extensions/db/fields/encrypted.py
Original file line number Diff line number Diff line change
@@ -10,21 +10,23 @@
raise ImportError('Using an encrypted field requires the Keyczar module. '
'You can obtain Keyczar from http://www.keyczar.org/.')

class EncryptionWarning(RuntimeWarning): pass

class EncryptionWarning(RuntimeWarning):
pass


class BaseEncryptedField(models.Field):
prefix = 'enc_str:::'

def __init__(self, *args, **kwargs):
if not hasattr(settings, 'ENCRYPTED_FIELD_KEYS_DIR'):
raise ImproperlyConfigured('You must set the '
'ENCRYPTED_FIELD_KEYS_DIR setting to your Keyczar keys directory.')
raise ImproperlyConfigured('You must set the ENCRYPTED_FIELD_KEYS_DIR setting to your Keyczar keys directory.')
self.crypt = keyczar.Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR)

# Encrypted size is larger than unencrypted
self.unencrypted_length = max_length = kwargs.get('max_length', None)
if max_length:
max_length = len(self.prefix) + \
len(self.crypt.Encrypt('x'*max_length))
max_length = len(self.prefix) + len(self.crypt.Encrypt('x' * max_length))
# TODO: Re-examine if this logic will actually make a large-enough
# max-length for unicode strings that have non-ascii characters in them.
kwargs['max_length'] = max_length
@@ -50,8 +52,9 @@ def get_db_prep_value(self, value, connection, prepared=False):
# so truncate before encryption
max_length = self.unencrypted_length
if max_length and len(value) > max_length:
warnings.warn("Truncating field %s from %d to %d bytes" % \
(self.name, len(value), max_length),EncryptionWarning)
warnings.warn("Truncating field %s from %d to %d bytes" % (
self.name, len(value), max_length), EncryptionWarning
)
value = value[:max_length]

value = self.prefix + self.crypt.Encrypt(value)
2 changes: 1 addition & 1 deletion django_extensions/db/fields/json.py
Original file line number Diff line number Diff line change
@@ -15,7 +15,6 @@ class LOL(models.Model):
from django.db import models
from django.conf import settings
from django.utils import simplejson
from django.utils.encoding import smart_unicode


class JSONEncoder(simplejson.JSONEncoder):
@@ -49,6 +48,7 @@ class JSONDict(dict):
def __repr__(self):
return dumps(self)


class JSONList(list):
"""
As above
10 changes: 4 additions & 6 deletions django_extensions/db/models.py
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@

try:
from django.utils.timezone import now as datetime_now
assert datetime_now
except ImportError:
import datetime
datetime_now = datetime.datetime.now
@@ -62,12 +63,9 @@ class ActivatorModel(models.Model):
(INACTIVE_STATUS, _('Inactive')),
(ACTIVE_STATUS, _('Active')),
)
status = models.IntegerField(_('status'), choices=STATUS_CHOICES,
default=ACTIVE_STATUS)
activate_date = models.DateTimeField(blank=True, null=True,
help_text=_('keep empty for an immediate activation'))
deactivate_date = models.DateTimeField(blank=True, null=True,
help_text=_('keep empty for indefinite activation'))
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=ACTIVE_STATUS)
activate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for an immediate activation'))
deactivate_date = models.DateTimeField(blank=True, null=True, help_text=_('keep empty for indefinite activation'))
objects = ActivatorModelManager()

class Meta:
7 changes: 4 additions & 3 deletions django_extensions/jobs/daily/cache_cleanup.py
Original file line number Diff line number Diff line change
@@ -34,7 +34,8 @@ def execute(self):
os.environ['TZ'] = settings.TIME_ZONE
table_name = settings.CACHE_BACKEND[5:]
cursor = connection.cursor()
cursor.execute("DELETE FROM %s WHERE %s < current_timestamp;" % \
(connection.ops.quote_name(table_name),
connection.ops.quote_name('expires')))
cursor.execute("DELETE FROM %s WHERE %s < current_timestamp;" % (
connection.ops.quote_name(table_name),
connection.ops.quote_name('expires'))
)
transaction.commit_unless_managed()
9 changes: 4 additions & 5 deletions django_extensions/management/commands/clean_pyc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.core.management.base import NoArgsCommand
from django_extensions.management.utils import get_project_root
from random import choice
from optparse import make_option
from os.path import join as _j
import os
@@ -9,9 +8,9 @@
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--optimize', '-o', '-O', action='store_true', dest='optimize',
help='Remove optimized python bytecode files'),
help='Remove optimized python bytecode files'),
make_option('--path', '-p', action='store', dest='path',
help='Specify path to recurse into'),
help='Specify path to recurse into'),
)
help = "Removes all python bytecode compiled files from the project."

@@ -40,6 +39,6 @@ def handle_noargs(self, **options):
if not [opt for opt in Command.option_list if opt.dest == 'verbosity']:
Command.option_list += (
make_option('--verbosity', '-v', action="store", dest="verbosity",
default='1', type='choice', choices=['0', '1', '2'],
help="Verbosity level; 0=minimal output, 1=normal output, 2=all output"),
default='1', type='choice', choices=['0', '1', '2'],
help="Verbosity level; 0=minimal output, 1=normal output, 2=all output"),
)
8 changes: 3 additions & 5 deletions django_extensions/management/commands/compile_pyc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.core.management.base import NoArgsCommand
from django_extensions.management.utils import get_project_root
from random import choice
from optparse import make_option
from os.path import join as _j
import py_compile
@@ -9,8 +8,7 @@

class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--path', '-p', action='store', dest='path',
help='Specify path to recurse into'),
make_option('--path', '-p', action='store', dest='path', help='Specify path to recurse into'),
)
help = "Compile python bytecode files for the project."

@@ -35,6 +33,6 @@ def handle_noargs(self, **options):
if not [opt for opt in Command.option_list if opt.dest == 'verbosity']:
Command.option_list += (
make_option('--verbosity', '-v', action="store", dest="verbosity",
default='1', type='choice', choices=['0', '1', '2'],
help="Verbosity level; 0=minimal output, 1=normal output, 2=all output"),
default='1', type='choice', choices=['0', '1', '2'],
help="Verbosity level; 0=minimal output, 1=normal output, 2=all output"),
)
34 changes: 13 additions & 21 deletions django_extensions/management/commands/create_app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import re
import sys
import django_extensions
from django.conf import settings
from django.db import connection
@@ -14,17 +15,16 @@
class Command(LabelCommand):
option_list = LabelCommand.option_list + (
make_option('--template', '-t', action='store', dest='app_template',
help='The path to the app template'),
help='The path to the app template'),
make_option('--parent_path', '-p', action='store', dest='parent_path',
help='The parent path of the application to be created'),
help='The parent path of the application to be created'),
make_option('-d', action='store_true', dest='dia_parse',
help='Generate model.py and admin.py from [APP_NAME].dia file'),
help='Generate model.py and admin.py from [APP_NAME].dia file'),
make_option('--diagram', action='store', dest='dia_path',
help='The diagram path of the app to be created. -d is implied'),
help='The diagram path of the app to be created. -d is implied'),
)

help = ("Creates an application directory structure for the specified "
"application name.")
help = ("Creates an application directory structure for the specified application name.")
args = "APP_NAME"
label = 'application name'

@@ -48,17 +48,12 @@ def handle_label(self, label, **options):
dia_parse = options.get('dia_path') or options.get('dia_parse')
if dia_parse:
if not os.path.exists(dia_path):
raise CommandError("The diagram path, %r, does not exist."
% dia_path)
raise CommandError("The diagram path, %r, does not exist." % dia_path)
if app_name in settings.INSTALLED_APPS:
raise CommandError("The application %s should not be defined "
"in the settings file. Please remove %s now, and add it "
"after using this command." % (app_name, app_name))
tables = [name for name in connection.introspection.table_names()
if name.startswith('%s_' % app_name)]
raise CommandError("The application %s should not be defined in the settings file. Please remove %s now, and add it after using this command." % (app_name, app_name))
tables = [name for name in connection.introspection.table_names() if name.startswith('%s_' % app_name)]
if tables:
raise CommandError("%r application has tables in the database. "
"Please delete them." % app_name)
raise CommandError("%r application has tables in the database. Please delete them." % app_name)

try:
os.makedirs(app_dir)
@@ -110,7 +105,7 @@ def copy_template(app_template, copy_to, project_name, app_name):
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except OSError:
sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)


def generate_models_and_admin(dia_path, app_dir, project_name, app_name):
@@ -139,9 +134,6 @@ def format_text(string, indent=False):
open(model_path, 'w').write(models_txt)

classes = re.findall('class (\w+)', models_txt)
admin_txt = 'from django.contrib.admin import site, ModelAdmin\n' + \
format_text('from %s.%s.models import %s' %
(project_name, app_name, ', '.join(classes)), indent=True)
admin_txt += format_text('\n\n%s' %
'\n'.join(map((lambda t: 'site.register(%s)' % t), classes)))
admin_txt = 'from django.contrib.admin import site, ModelAdmin\n' + format_text('from %s.%s.models import %s' % (project_name, app_name, ', '.join(classes)), indent=True)
admin_txt += format_text('\n\n%s' % '\n'.join(map((lambda t: 'site.register(%s)' % t), classes)))
open(admin_path, 'w').write(admin_txt)
8 changes: 4 additions & 4 deletions django_extensions/management/commands/create_command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import sys
from django.core.management.base import CommandError, AppCommand
from django_extensions.management.utils import _make_writeable
from optparse import make_option
@@ -7,9 +8,9 @@
class Command(AppCommand):
option_list = AppCommand.option_list + (
make_option('--name', '-n', action='store', dest='command_name', default='sample',
help='The name to use for the management command'),
help='The name to use for the management command'),
make_option('--base', '-b', action='store', dest='base_command', default='Base',
help='The base class used for implementation of this command. Should be one of Base, App, Label, or NoArgs'),
help='The base class used for implementation of this command. Should be one of Base, App, Label, or NoArgs'),
)

help = ("Creates a Django management command directory structure for the given app name"
@@ -38,7 +39,6 @@ def handle_app(self, app, **options):
def copy_template(template_name, copy_to, command_name, base_command):
"""copies the specified template directory to the copy_to location"""
import django_extensions
import re
import shutil

template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)
@@ -78,4 +78,4 @@ def copy_template(template_name, copy_to, command_name, base_command):
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except OSError:
sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
5 changes: 2 additions & 3 deletions django_extensions/management/commands/create_jobs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
import sys
from django.core.management.base import CommandError, AppCommand
from django.core.management.base import AppCommand
from django_extensions.management.utils import _make_writeable


@@ -22,7 +22,6 @@ def handle_app(self, app, **options):
def copy_template(template_name, copy_to):
"""copies the specified template directory to the copy_to location"""
import django_extensions
import re
import shutil

template_dir = os.path.join(django_extensions.__path__[0], 'conf', template_name)
@@ -54,4 +53,4 @@ def copy_template(template_name, copy_to):
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except OSError:
sys.stderr.write(style.NOTICE("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new))
sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
2 changes: 1 addition & 1 deletion django_extensions/management/commands/describe_form.py
Original file line number Diff line number Diff line change
@@ -38,7 +38,7 @@ def describe_form(label, fields=None):
attrs = {}
valid_fields = ['required', 'initial', 'max_length', 'min_length', 'max_value', 'min_value', 'max_digits', 'decimal_places', 'choices', 'help_text', 'label']
for k, v in formfield.__dict__.items():
if k in valid_fields and v != None:
if k in valid_fields and v is not None:
# ignore defaults, to minimize verbosity
if k == 'required' and v:
continue
Loading

0 comments on commit a39e554

Please sign in to comment.