Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Correct flake8 errors and warnings

  • Loading branch information...
commit 5316b7531427942a81eead1af37e0f1cc0911041 1 parent 55fb5cf
@codeinthehole codeinthehole authored
View
15 oscar/core/application.py
@@ -3,23 +3,24 @@
class Application(object):
name = None
-
+
def __init__(self, app_name=None, **kwargs):
self.app_name = app_name
# Set all kwargs as object attributes
for key, value in kwargs.iteritems():
setattr(self, key, value)
-
+
def get_urls(self):
"""
- Return the url patterns for this app, MUST be implemented in the subclass
+ Return the url patterns for this app, MUST be implemented in the
+ subclass
"""
return patterns('')
def post_process_urls(self, urlpatterns):
"""
- Customise URL patterns.
-
+ Customise URL patterns.
+
By default, this only allows custom decorators to be specified, but you
could override this method to do anything you want.
"""
@@ -35,8 +36,8 @@ def post_process_urls(self, urlpatterns):
def get_url_decorator(self, url_name):
return None
-
+
@property
def urls(self):
# We set the application and instance namespace here
- return self.get_urls(), self.app_name, self.name
+ return self.get_urls(), self.app_name, self.name
View
3  oscar/core/context_processors.py
@@ -9,4 +9,5 @@ def metadata(request):
'version': getattr(settings, 'VERSION', 'N/A'),
'shop_name': settings.OSCAR_SHOP_NAME,
'shop_tagline': settings.OSCAR_SHOP_TAGLINE,
- 'google_analytics_id': getattr(settings, 'GOOGLE_ANALYTICS_ID', None)}
+ 'google_analytics_id': getattr(settings,
+ 'GOOGLE_ANALYTICS_ID', None)}
View
5 oscar/core/loading.py
@@ -44,7 +44,7 @@ class can't be found in the overriding module, then we attempt to import it
# App must be local - check if module is in local app (it could be in
# oscar's)
app_label = module_label.split('.')[0]
- base_package = app_module_path.rsplit('.'+app_label, 1)[0]
+ base_package = app_module_path.rsplit('.' + app_label, 1)[0]
local_app = "%s.%s" % (base_package, module_label)
try:
imported_local_module = __import__(local_app, fromlist=classnames)
@@ -54,7 +54,8 @@ class can't be found in the overriding module, then we attempt to import it
oscar_app = "oscar.apps.%s" % module_label
imported_oscar_module = __import__(oscar_app, fromlist=classnames)
- return _pluck_classes([imported_local_module, imported_oscar_module], classnames)
+ return _pluck_classes([imported_local_module, imported_oscar_module],
+ classnames)
def _pluck_classes(modules, classnames):
View
7 oscar/core/logging/formatters.py
@@ -4,11 +4,10 @@
class PciFormatter(Formatter):
"""
- Strip card numbers out of log messages to avoid leaving sensitive information
- in the logs.
+ Strip card numbers out of log messages to avoid leaving sensitive
+ information in the logs.
"""
-
+
def format(self, record):
s = Formatter.format(self, record)
return re.sub(r'\d[ \d-]{15,22}', 'XXXX-XXXX-XXXX-XXXX', s)
-
View
12 oscar/core/logging/handlers.py
@@ -6,21 +6,21 @@ class EnvFileHandler(BaseFileHandler):
"""
Custom filehandler that uses the LOG_ROOT setting to determine the folder
to store log files in.
-
- We have to do some tricky stuff to avoid circular imports. To this end,
- we pass /dev/null to the parent handler but specify opening to be delayed.
+
+ We have to do some tricky stuff to avoid circular imports. To this end,
+ we pass /dev/null to the parent handler but specify opening to be delayed.
Then when we try to first open the file, we join the LOG_ROOT with the
passed filename.
"""
-
+
def __init__(self, filename, *args, **kwargs):
self.filename = filename
kwargs['delay'] = True
BaseFileHandler.__init__(self, "/dev/null", *args, **kwargs)
-
+
def _open(self):
# We import settings here to avoid a circular reference as this module
# will be imported when settings.py is executed.
from django.conf import settings
self.baseFilename = os.path.join(settings.LOG_ROOT, self.filename)
- return BaseFileHandler._open(self)
+ return BaseFileHandler._open(self)
View
8 oscar/core/validators.py
@@ -1,12 +1,10 @@
-import re
-
from django.core import validators
from django.core.exceptions import ValidationError
from django.core.urlresolvers import resolve
+from django.db.models import get_model
from django.http import Http404
from django.utils.translation import ugettext_lazy as _
-from django.db.models import get_model
class ExtendedURLValidator(validators.URLValidator):
def __call__(self, value):
@@ -77,7 +75,7 @@ def __call__(self, value):
super(URLDoesNotExistValidator, self).__call__(value)
except ValidationError:
raise ValidationError(_('Specified page does already exist'),
- code='invalid')
+ code='invalid')
# check if URL exists since it seems to be valid
try:
@@ -87,4 +85,4 @@ def __call__(self, value):
return
raise ValidationError(_('Specified page does already exist'),
- code='invalid')
+ code='invalid')
View
8 oscar/defaults.py
@@ -2,7 +2,7 @@
OSCAR_SHOP_TAGLINE = 'Domain-driven e-Commerce for Django'
# Basket settings
-OSCAR_BASKET_COOKIE_LIFETIME = 7*24*60*60
+OSCAR_BASKET_COOKIE_LIFETIME = 7 * 24 * 60 * 60
OSCAR_BASKET_COOKIE_OPEN = 'oscar_open_basket'
OSCAR_BASKET_COOKIE_SAVED = 'oscar_saved_basket'
@@ -31,7 +31,8 @@
OSCAR_PARTNER_WRAPPERS = {}
# Promotions
-COUNTDOWN, LIST, SINGLE_PRODUCT, TABBED_BLOCK = ('Countdown', 'List', 'SingleProduct', 'TabbedBlock')
+COUNTDOWN, LIST, SINGLE_PRODUCT, TABBED_BLOCK = (
+ 'Countdown', 'List', 'SingleProduct', 'TabbedBlock')
OSCAR_PROMOTION_MERCHANDISING_BLOCK_TYPES = (
(COUNTDOWN, "Vertical list"),
(LIST, "Horizontal list"),
@@ -56,4 +57,5 @@
# Cookies
OSCAR_COOKIES_DELETE_ON_LOGOUT = ['oscar_recently_viewed_products', ]
-OSCAR_SETTINGS = dict([(k, v) for k, v in locals().items() if k.startswith('OSCAR_')])
+OSCAR_SETTINGS = dict(
+ [(k, v) for k, v in locals().items() if k.startswith('OSCAR_')])
View
13 oscar/forms/fields.py
@@ -3,19 +3,21 @@
from oscar.core import validators
+
class ExtendedURLField(fields.URLField):
"""
- Custom field similar to URLField type field, however also accepting
- and validating local relative URLs, ie. '/product/'
+ Custom field similar to URLField type field, however also accepting and
+ validating local relative URLs, ie. '/product/'
"""
def __init__(self, max_length=None, min_length=None, verify_exists=False,
validator_user_agent=URL_VALIDATOR_USER_AGENT, *args, **kwargs):
# intentionally skip one step when calling super()
super(fields.URLField, self).__init__(max_length, min_length, *args,
- **kwargs)
- validator = validators.ExtendedURLValidator(verify_exists=verify_exists,
- validator_user_agent=validator_user_agent)
+ **kwargs)
+ validator = validators.ExtendedURLValidator(
+ verify_exists=verify_exists,
+ validator_user_agent=validator_user_agent)
self.validators.append(validator)
def to_python(self, value):
@@ -24,4 +26,3 @@ def to_python(self, value):
if value and value.startswith('/'):
return value
return super(ExtendedURLField, self).to_python(value)
-
View
7 oscar/management/commands/oscar_calculate_scores.py
@@ -10,11 +10,6 @@
class Command(BaseCommand):
help = 'Calculate product scores based on analytics data'
-
+
def handle(self, *args, **options):
Calculator(logger).run()
-
-
-
-
-
View
13 oscar/management/commands/oscar_generate_email_content.py
@@ -10,16 +10,17 @@
class Command(BaseCommand):
args = '<communication_event_type> <order number>'
help = 'For testing the content of order emails'
-
+
def handle(self, *args, **options):
if len(args) != 2:
raise CommandError("Please select a event type and order number")
-
+
try:
order = Order.objects.get(number=args[1])
except Order.DoesNotExist:
raise CommandError("No order found with number %s" % args[1])
-
- messages = CommunicationEventType.objects.get_and_render(args[0], {'order': order})
- print "Subject: %s\nBody:\n\n%s\nBody HTML:\n\n%s"% (
- messages['subject'], messages['body'], messages['html'])
+
+ messages = CommunicationEventType.objects.get_and_render(
+ args[0], {'order': order})
+ print "Subject: %s\nBody:\n\n%s\nBody HTML:\n\n%s" % (
+ messages['subject'], messages['body'], messages['html'])
View
14 oscar/management/commands/oscar_import_catalogue.py
@@ -11,7 +11,7 @@
class Command(BaseCommand):
args = '/path/to/file1.csv /path/to/file2.csv ...'
help = 'For creating product catalogues based on a CSV file'
-
+
option_list = BaseCommand.option_list + (
make_option('--flush',
action='store_true',
@@ -28,23 +28,21 @@ def handle(self, *args, **options):
logger = self._get_logger()
if not args:
raise CommandError("Please select a CSV file to import")
-
+
logger.info("Starting catalogue import")
- importer = CatalogueImporter(logger, delimiter=options.get('delimiter'), flush=options.get('flush'))
+ importer = CatalogueImporter(logger,
+ delimiter=options.get('delimiter'),
+ flush=options.get('flush'))
for file_path in args:
logger.info(" - Importing records from '%s'" % file_path)
try:
importer.handle(file_path)
except CatalogueImportError, e:
raise CommandError(str(e))
-
+
def _get_logger(self):
logger = logging.getLogger(__file__)
stream = logging.StreamHandler(self.stdout)
logger.addHandler(stream)
logger.setLevel(logging.DEBUG)
return logger
-
-
-
-
View
14 oscar/management/commands/oscar_import_catalogue_images.py
@@ -8,10 +8,9 @@
class Command(BaseCommand):
-
args = '/path/to/folder'
help = 'For importing product images from a folder'
-
+
option_list = BaseCommand.option_list + (
make_option('--filename',
dest='filename',
@@ -21,19 +20,18 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if len(args) != 1:
- raise CommandError('Command requires a path to a single folder')
-
+ raise CommandError('Command requires a path to a single folder')
+
logger = self._get_logger()
- logger.info("Starting image import...")
-
+ logger.info("Starting image import...")
+
dirname = args[0]
importer = Importer(logger, field=options.get('filename'))
importer.handle(dirname)
-
+
def _get_logger(self):
logger = logging.getLogger('oscar.apps.image')
stream = logging.StreamHandler(self.stdout)
logger.addHandler(stream)
logger.setLevel(logging.DEBUG)
return logger
-
View
18 oscar/management/commands/oscar_import_stock.py
@@ -9,10 +9,9 @@
class Command(BaseCommand):
-
args = '<partner> /path/to/file1.csv'
help = 'For updating stock for a partner based on a CSV file'
-
+
option_list = BaseCommand.option_list + (
make_option('--delimiter',
dest='delimiter',
@@ -22,21 +21,24 @@ class Command(BaseCommand):
def handle(self, *args, **options):
if len(args) != 2:
- raise CommandError('Command requires a partner and a path to a csv file')
-
+ raise CommandError(
+ 'Command requires a partner and a path to a csv file')
+
logger = self._get_logger()
-
+
try:
- importer = StockImporter(logger, partner=args[0], delimiter=options.get('delimiter'))
+ importer = StockImporter(logger,
+ partner=args[0],
+ delimiter=options.get('delimiter'))
logger.info("Starting stock import")
logger.info(" - Importing records from '%s'" % args[1])
importer.handle(args[1])
except ImportError, e:
raise CommandError(str(e))
-
+
def _get_logger(self):
logger = logging.getLogger('oscar.apps.partner.import_stock')
stream = logging.StreamHandler(self.stdout)
logger.addHandler(stream)
logger.setLevel(logging.DEBUG)
- return logger
+ return logger
View
12 oscar/models/fields.py
@@ -10,20 +10,24 @@
pass
else:
add_introspection_rules([], ["^oscar\.models\.fields\.ExtendedURLField$"])
- add_introspection_rules([], ["^oscar\.models\.fields\.PositiveDecimalField$"])
+ add_introspection_rules([], [
+ "^oscar\.models\.fields\.PositiveDecimalField$"])
class ExtendedURLField(CharField):
description = _("URL")
- def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
+ def __init__(self, verbose_name=None, name=None,
+ verify_exists=True, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
CharField.__init__(self, verbose_name, name, **kwargs)
- validator = validators.ExtendedURLValidator(verify_exists=verify_exists)
+ validator = validators.ExtendedURLValidator(
+ verify_exists=verify_exists)
self.validators.append(validator)
def formfield(self, **kwargs):
- # As with CharField, this will cause URL validation to be performed twice
+ # As with CharField, this will cause URL validation to be performed
+ # twice.
defaults = {
'form_class': fields.ExtendedURLField,
}
View
20 oscar/templatetags/basket_tags.py
@@ -10,6 +10,7 @@
QNT_SINGLE, QNT_MULTIPLE = 'single', 'multiple'
+
@register.tag(name="basket_form")
def do_basket_form(parse, token):
"""
@@ -18,13 +19,18 @@ def do_basket_form(parse, token):
"""
tokens = token.split_contents()
if len(tokens) < 4 or tokens[3] != 'as':
- raise template.TemplateSyntaxError("%r tag uses the following syntax: {%% basket_form basket_var product_var as form_var %%}" % tokens[0])
+ raise template.TemplateSyntaxError(
+ "%r tag uses the following syntax: "
+ "{%% basket_form basket_var product_var as "
+ "form_var %%}" % tokens[0])
basket_var, product_var, form_var = tokens[1], tokens[2], tokens[4]
quantity_type = tokens[5] if len(tokens) == 6 else QNT_MULTIPLE
if quantity_type not in (QNT_SINGLE, QNT_MULTIPLE):
- raise template.TemplateSyntaxError("%r tag only accepts the following quantity types: 'single', 'multiple'" % tokens[0])
+ raise template.TemplateSyntaxError(
+ "%r tag only accepts the following quantity types: "
+ "'single', 'multiple'" % tokens[0])
return BasketFormNode(basket_var, product_var, form_var, quantity_type)
@@ -33,7 +39,8 @@ def __init__(self, basket_var, product_var, form_var, quantity_type):
self.basket_var = template.Variable(basket_var)
self.product_var = template.Variable(product_var)
self.form_var = form_var
- self.form_class = AddToBasketForm if quantity_type == QNT_MULTIPLE else SimpleAddToBasketForm
+ self.form_class = (AddToBasketForm if quantity_type == QNT_MULTIPLE
+ else SimpleAddToBasketForm)
def render(self, context):
try:
@@ -46,5 +53,8 @@ def render(self, context):
initial = {}
if not product.is_group:
initial['product_id'] = product.id
- context[self.form_var] = self.form_class(basket, user=None, instance=product, initial=initial)
- return ''
+ context[self.form_var] = self.form_class(basket,
+ user=None,
+ instance=product,
+ initial=initial)
+ return ''
View
18 oscar/templatetags/category_tags.py
@@ -2,12 +2,14 @@
from django.db.models import get_model
register = template.Library()
-Category = get_model('catalogue','category')
+Category = get_model('catalogue', 'category')
+
@register.tag(name="category_tree")
def do_category_list(parse, token):
tokens = token.split_contents()
- error_msg = "%r tag uses the following syntax: {%% category_tree [depth=n] as categories %%}" % tokens[0]
+ error_msg = ("%r tag uses the following syntax: {%% category_tree "
+ "[depth=n] as categories %%}" % tokens[0])
depth_var = '1'
if len(tokens) == 4:
@@ -21,7 +23,7 @@ def do_category_list(parse, token):
as_var = tokens[2]
else:
raise template.TemplateSyntaxError(error_msg)
-
+
return CategoryTreeNode(depth_var, as_var)
@@ -29,13 +31,13 @@ class CategoryTreeNode(template.Node):
def __init__(self, depth_var, as_var):
self.depth_var = template.Variable(depth_var)
self.as_var = as_var
-
+
def _build_tree(self, root, parent, data, depth):
for category in data[depth]:
if not parent or category.is_child_of(parent):
node = (category, [])
if depth < len(data) - 1:
- self._build_tree(node[1], category, data, depth+1)
+ self._build_tree(node[1], category, data, depth + 1)
root.append(node)
return root
@@ -47,12 +49,12 @@ def render(self, context):
categories = self.get_category_queryset(depth)
category_buckets = [[] for i in range(depth)]
-
+
for c in categories:
category_buckets[c.depth - 1].append(c)
category_subtree = []
-
+
self._build_tree(category_subtree, None, category_buckets, 0)
-
+
context[self.as_var] = category_subtree
return ''
View
5 oscar/templatetags/currency_filters.py
@@ -5,6 +5,7 @@
register = template.Library()
+
@register.filter(name='currency')
def currency(value):
"""
@@ -19,10 +20,10 @@ def currency(value):
symbol = getattr(settings, 'CURRENCY_SYMBOL', None)
try:
if symbol:
- return u"%s%s" % (symbol, locale.format("%.2f", value, grouping=True))
+ return u"%s%s" % (symbol, locale.format("%.2f",
+ value, grouping=True))
else:
c = locale.currency(value, symbol=True, grouping=True)
return unicode(c, 'utf8')
except TypeError:
return ''
-
View
5 oscar/templatetags/dashboard_tags.py
@@ -1,5 +1,4 @@
from django import template
-from django.core.urlresolvers import reverse
from oscar.core.loading import get_class
Order = get_class('order.models', 'Order')
@@ -13,7 +12,8 @@ def get_num_user_orders(parser, token):
tag_name, user = token.split_contents()
return NumUserOrdersNode(user)
except IndexError:
- raise template.TemplateSyntaxError("%r tag requires a user as it's first argument" % tag_name)
+ raise template.TemplateSyntaxError(
+ "%r tag requires a user as it's first argument" % tag_name)
class NumUserOrdersNode(template.Node):
@@ -40,4 +40,3 @@ def render(self, context):
register.tag('dashboard_navigation', dashboard_navigation)
-
View
5 oscar/templatetags/display_tags.py
@@ -10,7 +10,8 @@ def get_parameters(parser, token):
args = token.split_contents()
if len(args) < 2:
- raise template.TemplateSyntaxError, "get_parameters tag takes at least 1 argument"
+ raise template.TemplateSyntaxError(
+ "get_parameters tag takes at least 1 argument")
return GetParametersNode(args[1].strip())
@@ -35,4 +36,4 @@ def render(self, context):
return get_params
-get_parameters = register.tag(get_parameters)
+get_parameters = register.tag(get_parameters)
View
4 oscar/templatetags/history_tags.py
@@ -8,7 +8,9 @@
register = template.Library()
-@register.inclusion_tag('customer/history/recently-viewed-products.html', takes_context=True)
+
+@register.inclusion_tag('customer/history/recently-viewed-products.html',
+ takes_context=True)
def recently_viewed_products(context):
u"""
Inclusion tag listing the most recently viewed products
View
18 oscar/templatetags/image_tags.py
@@ -9,7 +9,8 @@ def do_dynamic_image_url(parser, token):
tokens = token.split_contents()
if len(tokens) < 2:
- raise template.TemplateSyntaxError("%r tag requires at least an image URL or field" % tokens[0])
+ raise template.TemplateSyntaxError(
+ "%r tag requires at least an image URL or field" % tokens[0])
image = tokens[1]
@@ -30,7 +31,9 @@ def __init__(self, image, params):
bits = p.split('=')
self.params[bits[0]] = template.Variable(bits[1])
except IndexError:
- raise template.TemplateSyntaxError("image tag parameters must be of form key=value, you used '%s'" % p)
+ raise template.TemplateSyntaxError(
+ "image tag parameters must be of form key=value, "
+ "you used '%s'" % p)
def render(self, context):
if isinstance(self.image, ImageFieldFile):
@@ -38,23 +41,21 @@ def render(self, context):
else:
path = self.image
- host = getattr(settings,'DYNAMIC_MEDIA_URL', None)
+ host = getattr(settings, 'DYNAMIC_MEDIA_URL', None)
if host:
params = []
-
ext = path[path.rfind('.') + 1:]
ext_changed = False
-
+
for key, v in self.params.iteritems():
value = v.resolve(context)
-
if key == u'format':
ext = value
ext_changed = True
else:
params.append('%s-%s' % (key, value))
-
+
if len(params) > 0:
suffix = '_'.join(params)
path = '.'.join((path, suffix, ext))
@@ -64,8 +65,7 @@ def render(self, context):
path = '.'.join((path, ext))
else:
path = '.'.join((path, 'to', ext))
-
-
return host + path
+
register.tag('image', do_dynamic_image_url)
View
18 oscar/templatetags/promotion_tags.py
@@ -1,26 +1,28 @@
-from django.template import Library, Node, Variable, Context
+from django.template import Library, Node, Variable
from django.template.loader import select_template
from django.template import RequestContext
-
+
register = Library()
-
-
+
+
class PromotionNode(Node):
def __init__(self, promotion):
self.promotion_var = Variable(promotion)
-
+
def render(self, context):
promotion = self.promotion_var.resolve(context)
- template = select_template([promotion.template_name(), 'promotions/default.html'])
+ template = select_template([promotion.template_name(),
+ 'promotions/default.html'])
args = {'promotion': promotion}
args.update(**promotion.template_context(request=context['request']))
ctx = RequestContext(context['request'], args)
return template.render(ctx)
-
+
+
def get_promotion_html(parser, token):
_, promotion = token.split_contents()
return PromotionNode(promotion)
-register.tag('render_promotion', get_promotion_html)
+register.tag('render_promotion', get_promotion_html)
View
2  oscar/templatetags/sorting_tags.py
@@ -1 +1 @@
-from django_sorting.templatetags.sorting_tags import *
+from django_sorting.templatetags.sorting_tags import *

0 comments on commit 5316b75

Please sign in to comment.
Something went wrong with that request. Please try again.