Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix linter warnings
Patryk Zawadzki43649e3b9d5f
diff --git a/saleor/__init__.py b/saleor/__init__.pyindex 4fe58bb95c..f3c916b5fb 100644--- a/saleor/__init__.py+++ b/saleor/__init__.py@@ -6,5 +6,5 @@ def manage():import sysfrom django.core.management import execute_from_command_line- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')execute_from_command_line(sys.argv)diff --git a/saleor/cart/middleware.py b/saleor/cart/middleware.pyindex 5c035edddf..9004907c5a 100644--- a/saleor/cart/middleware.py+++ b/saleor/cart/middleware.py@@ -4,10 +4,7 @@ from . import SessionCart, CART_SESSION_KEYclass CartMiddleware(object):- '''- Saves the cart instance into the django session.- '''-+ """Bind cart to a request and stores it in Django session"""def process_request(self, request):try:cart_data = request.session[CART_SESSION_KEY]diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex 40a96afc6f..e69de29bb2 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -1 +0,0 @@-# -*- coding: utf-8 -*-diff --git a/saleor/cart/test_cart.py b/saleor/cart/test_cart.pyindex 3fb079dd66..83c9315584 100755--- a/saleor/cart/test_cart.py+++ b/saleor/cart/test_cart.py@@ -1,9 +1,6 @@from __future__ import unicode_literalsfrom decimal import Decimal-from django.db import models-from django.test import TestCase-from django.utils.encoding import smart_textfrom mock import MagicMock, patchfrom prices import Priceimport pytest@@ -54,9 +51,6 @@ class ShipPhotoVariant(ProductVariant):def display_variant(self, attributes=None):return 'SHIP PHOTO'- def display_variant(self, attributes=None):- return 'BIG SHIP'-class ShipPhoto(Product):diff --git a/saleor/checkout/__init__.py b/saleor/checkout/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/checkout/__init__.py+++ b/saleor/checkout/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/checkout/core.py b/saleor/checkout/core.pyindex 4decb644e5..c5907340f4 100644--- a/saleor/checkout/core.py+++ b/saleor/checkout/core.py@@ -45,8 +45,8 @@ class Checkout(ProcessManager):shipping_address = self.shipping_address_step.addressself.steps.append(self.shipping_address_step)self.shipping_method_step = ShippingMethodStep(- self.request, self.storage['shipping_method'], shipping_address,- self.cart, checkout=self)+ self.request, self.storage['shipping_method'],+ shipping_address, self.cart, checkout=self)self.steps.append(self.shipping_method_step)else:shipping_address = Nonediff --git a/saleor/checkout/test_checkout.py b/saleor/checkout/test_checkout.pyindex 74c3ef89c6..f9bf7e7a3a 100644--- a/saleor/checkout/test_checkout.py+++ b/saleor/checkout/test_checkout.py@@ -223,7 +223,8 @@ def test_shipping_method_step(rf):def test_shipping_method_reload_step(rf):new_shipping_method_name = 'another_shipping_method'- request = rf.post('/shipping-method/', {'method': new_shipping_method_name})+ request = rf.post('/shipping-method/',+ {'method': new_shipping_method_name})request.session = {STORAGE_SESSION_KEY: {}}shipping_method = MagicMock()shipping_method.get_delivery_total = MagicMock()@@ -391,4 +392,3 @@ def test_billing_step_anonymous_user_without_email_without_shipping(rf):step = SummaryStep(request, storage, shipping_address=None,checkout=checkout)assert not step.forms_are_valid()-diff --git a/saleor/core/countries.py b/saleor/core/countries.pyindex 735ac72e76..cb0e8afce9 100644--- a/saleor/core/countries.py+++ b/saleor/core/countries.py@@ -1,4 +1,4 @@-#coding: utf-8+# coding: utf-8from __future__ import unicode_literals@@ -122,7 +122,8 @@ COUNTRY_CHOICES = [('KZ', pgettext_lazy('Country', 'Kazakhstan')),('KE', pgettext_lazy('Country', 'Kenya')),('KI', pgettext_lazy('Country', 'Kiribati')),- ('KP', pgettext_lazy('Country', 'Korea, Democratic People\'s Republic of')),+ ('KP', pgettext_lazy('Country',+ 'Korea, Democratic People\'s Republic of')),('KR', pgettext_lazy('Country', 'Korea, Republic of')),('KW', pgettext_lazy('Country', 'Kuwait')),('KG', pgettext_lazy('Country', 'Kyrgyzstan')),@@ -136,7 +137,8 @@ COUNTRY_CHOICES = [('LT', pgettext_lazy('Country', 'Lithuania')),('LU', pgettext_lazy('Country', 'Luxembourg')),('MO', pgettext_lazy('Country', 'Macao')),- ('MK', pgettext_lazy('Country', 'Macedonia, The Former Yugoslav Republic of')),+ ('MK', pgettext_lazy('Country',+ 'Macedonia, The Former Yugoslav Republic of')),('MG', pgettext_lazy('Country', 'Madagascar')),('MW', pgettext_lazy('Country', 'Malawi')),('MY', pgettext_lazy('Country', 'Malaysia')),@@ -190,7 +192,8 @@ COUNTRY_CHOICES = [('RU', pgettext_lazy('Country', 'Russian Federation')),('RW', pgettext_lazy('Country', 'Rwanda')),('BL', pgettext_lazy('Country', 'Saint Barthélemy')),- ('SH', pgettext_lazy('Country', 'Saint Helena, Ascension And Tristan Da Cunha')),+ ('SH', pgettext_lazy('Country',+ 'Saint Helena, Ascension And Tristan Da Cunha')),('KN', pgettext_lazy('Country', 'Saint Kitts And Nevis')),('LC', pgettext_lazy('Country', 'Saint Lucia')),('MF', pgettext_lazy('Country', 'Saint Martin (French Part)')),@@ -211,7 +214,8 @@ COUNTRY_CHOICES = [('SB', pgettext_lazy('Country', 'Solomon Islands')),('SO', pgettext_lazy('Country', 'Somalia')),('ZA', pgettext_lazy('Country', 'South Africa')),- ('GS', pgettext_lazy('Country', 'South Georgia and the South Sandwich Islands')),+ ('GS', pgettext_lazy('Country',+ 'South Georgia and the South Sandwich Islands')),('ES', pgettext_lazy('Country', 'Spain')),('LK', pgettext_lazy('Country', 'Sri Lanka')),('SD', pgettext_lazy('Country', 'Sudan')),diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex c8f26b2fc1..36aa0952fa 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -16,7 +16,7 @@ class CheckHTML(object):if (settings.DEBUG andsettings.WARN_ABOUT_INVALID_HTML5_OUTPUT and200 <= response.status_code < 300):- proc = Popen(["tidy"], stdout=PIPE, stderr=PIPE, stdin=PIPE)+ proc = Popen(['tidy'], stdout=PIPE, stderr=PIPE, stdin=PIPE)_out, err = proc.communicate(response.content)for l in err.split('\n\n')[0].split('\n')[:-2]:logger.warning(l)diff --git a/saleor/core/templatetags/markdown.py b/saleor/core/templatetags/markdown.pyindex 4bb385be3a..85f94d63d8 100644--- a/saleor/core/templatetags/markdown.py+++ b/saleor/core/templatetags/markdown.py@@ -9,5 +9,5 @@ register = template.Library()@register.filterdef markdown(text):- html = format_markdown(text, safe_mode="escape", output_format="html5")+ html = format_markdown(text, safe_mode='escape', output_format='html5')return mark_safe(html)diff --git a/saleor/core/test_core.py b/saleor/core/test_core.pyindex 19b1ae85e3..9e597bcb4d 100644--- a/saleor/core/test_core.py+++ b/saleor/core/test_core.py@@ -28,12 +28,12 @@ class SimpleStepTest(TestCase):request = MagicMock()request.method = 'GET'step = SimpleStep(request)- self.assert_(step.forms_are_valid())+ assert step.forms_are_valid()def test_process(self):request = MagicMock()request.method = 'GET'step = SimpleStep(request)- self.assertEqual(type(step.process()), TemplateResponse)+ assert isinstance(step.process(), TemplateResponse)request.method = 'POST'- self.assertEqual(step.process(), None)+ assert step.process() is Nonediff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 2a7e8ff9c9..37e94b6b0b 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -15,7 +15,7 @@ except ImportError:__all__ = ['BaseStep', 'CategoryChoiceField', 'build_absolute_uri']-absolute_http_url_re = re.compile(r"^https?://", re.I)+absolute_http_url_re = re.compile(r'^https?://', re.I)class CategoryChoiceField(forms.ModelChoiceField):diff --git a/saleor/dashboard/__init__.py b/saleor/dashboard/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/dashboard/__init__.py+++ b/saleor/dashboard/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.pyindex f18871cd51..b5783ce934 100644--- a/saleor/dashboard/category/forms.py+++ b/saleor/dashboard/category/forms.py@@ -7,7 +7,6 @@ from ...product.models import Categoryclass CategoryForm(forms.ModelForm):-def __init__(self, *args, **kwargs):self.parent_pk = kwargs.pop('parent_pk')super(CategoryForm, self).__init__(*args, **kwargs)@@ -21,7 +20,8 @@ class CategoryForm(forms.ModelForm):def save(self, commit=True):self.instance.slug = slugify(unidecode(self.instance.name))if self.parent_pk:- self.instance.parent = get_object_or_404(Category, pk=self.parent_pk)+ self.instance.parent = get_object_or_404(+ Category, pk=self.parent_pk)if self.instance.parent and self.instance.parent.hidden:self.instance.hidden = Truesuper(CategoryForm, self).save(commit=commit)diff --git a/saleor/dashboard/customer/__init__.py b/saleor/dashboard/customer/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/dashboard/customer/__init__.py+++ b/saleor/dashboard/customer/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/dashboard/order/__init__.py b/saleor/dashboard/order/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/dashboard/order/__init__.py+++ b/saleor/dashboard/order/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 7aacf11d24..4df91022af 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -129,7 +129,8 @@ class ChangeQuantityForm(forms.ModelForm):def clean_quantity(self):quantity = self.cleaned_data['quantity']- variant = get_object_or_404(ProductVariant, sku=self.instance.product_sku)+ variant = get_object_or_404(+ ProductVariant, sku=self.instance.product_sku)try:variant.check_quantity(quantity)except InsufficientStock as e:@@ -170,10 +171,12 @@ ORDER_STATUS_CHOICES = (('', pgettext_lazy('Order status field value','All')),) + Order.STATUS_CHOICESPAYMENT_STATUS_CHOICES = (('', pgettext_lazy('Payment status field value',- 'All')),) + PAYMENT_STATUS_CHOICES+ 'All')),) + PAYMENT_STATUS_CHOICES+class OrderFilterForm(forms.Form):status = forms.ChoiceField(choices=ORDER_STATUS_CHOICES)+class PaymentFilterForm(forms.Form):status = forms.ChoiceField(choices=PAYMENT_STATUS_CHOICES)diff --git a/saleor/dashboard/order/urls.py b/saleor/dashboard/order/urls.pyindex 5b8187863a..b7d88e279d 100644--- a/saleor/dashboard/order/urls.py+++ b/saleor/dashboard/order/urls.py@@ -19,10 +19,9 @@ urlpatterns = [url(r'^(?P<order_pk>\d+)/payment/(?P<payment_pk>\d+)/refund/$',views.refund_payment, name='refund-payment'),- url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change/$', views.orderline_change_quantity,- name='orderline-change-quantity'),- url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/split/$', views.orderline_split,- name='orderline-split'),- url(r'^(?P<order_pk>\d+)/shipment/(?P<group_pk>\d+)/ship/$', views.ship_delivery_group,- name='ship-delivery-group')-]+ url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/change/$',+ views.orderline_change_quantity, name='orderline-change-quantity'),+ url(r'^(?P<order_pk>\d+)/line/(?P<line_pk>\d+)/split/$',+ views.orderline_split, name='orderline-split'),+ url(r'^(?P<order_pk>\d+)/shipment/(?P<group_pk>\d+)/ship/$',+ views.ship_delivery_group, name='ship-delivery-group')]diff --git a/saleor/dashboard/payments/__init__.py b/saleor/dashboard/payments/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/dashboard/payments/__init__.py+++ b/saleor/dashboard/payments/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/dashboard/payments/views.py b/saleor/dashboard/payments/views.pyindex b18fa5b078..548b18cba7 100644--- a/saleor/dashboard/payments/views.py+++ b/saleor/dashboard/payments/views.py@@ -8,6 +8,7 @@ from ..views import (FilterByStatusMixin, StaffMemberOnlyMixin,from ...order.models import Paymentfrom ..order.forms import PaymentFilterForm+class PaymentList(StaffMemberOnlyMixin, FilterByStatusMixin, ListView):model = Paymenttemplate_name = 'dashboard/payments/list.html'diff --git a/saleor/dashboard/product/__init__.py b/saleor/dashboard/product/__init__.pyindex 8b13789179..e69de29bb2 100644--- a/saleor/dashboard/product/__init__.py+++ b/saleor/dashboard/product/__init__.py@@ -1 +0,0 @@-diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 61d6f5ef20..75231685bd 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -47,12 +47,15 @@ class ProductForm(forms.ModelForm):def __init__(self, *args, **kwargs):super(ProductForm, self).__init__(*args, **kwargs)- self.fields['name'].widget.attrs['placeholder'] = pgettext_lazy(+ field = self.fields['name']+ field.widget.attrs['placeholder'] = pgettext_lazy('Product form labels', 'Give your awesome product a name')- self.fields['categories'].widget.attrs[- 'data-placeholder'] = pgettext_lazy('Product form labels', 'Search')- self.fields['attributes'].widget.attrs[- 'data-placeholder'] = pgettext_lazy('Product form labels', 'Search')+ field = self.fields['categories']+ field.widget.attrs['data-placeholder'] = pgettext_lazy(+ 'Product form labels', 'Search')+ field = self.fields['attributes']+ field.widget.attrs['data-placeholder'] = pgettext_lazy(+ 'Product form labels', 'Search')if self.instance.available_on:self.fields['available_on'].widget.attrs['datavalue'] = self.instance.available_on.strftime('%Y/%m/%d')@@ -81,7 +84,7 @@ class ProductVariantForm(forms.ModelForm):class CachingModelChoiceIterator(ModelChoiceIterator):def __iter__(self):if self.field.empty_label is not None:- yield ("", self.field.empty_label)+ yield ('', self.field.empty_label)for obj in self.queryset:yield self.choice(obj)@@ -101,8 +104,8 @@ class VariantAttributeForm(forms.ModelForm):def __init__(self, *args, **kwargs):super(VariantAttributeForm, self).__init__(*args, **kwargs)- self.available_attrs = self.instance.product.attributes.prefetch_related(- 'values')+ attrs = self.instance.product.attributes.all()+ self.available_attrs = attrs.prefetch_related('values')for attr in self.available_attrs:field_defaults = {'label': attr.display,'required': True,@@ -127,7 +130,8 @@ class VariantBulkDeleteForm(forms.Form):items = forms.ModelMultipleChoiceField(queryset=ProductVariant.objects)def delete(self):- items = ProductVariant.objects.filter(pk__in=self.cleaned_data['items'])+ items = ProductVariant.objects.filter(+ pk__in=self.cleaned_data['items'])items.delete()diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 99966c4366..fb5ad015f1 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -7,11 +7,11 @@ from django.utils.http import is_safe_urlfrom django.utils.translation import ugettext_lazy as _from django.views.decorators.http import require_http_methods+from . import formsfrom ...core.utils import get_paginator_items-from ...product.models import Product, ProductImage, Stock, ProductAttribute, \- ProductVariant+from ...product.models import (Product, ProductAttribute, ProductImage,+ ProductVariant, Stock)from ..views import staff_member_required-from . import forms@staff_member_required@@ -35,7 +35,8 @@ def product_create(request):messages.success(request, msg)return redirect('dashboard:variant-add', product_pk=product.pk)ctx = {'product_form': form, 'product': product}- return TemplateResponse(request, 'dashboard/product/product_form.html', ctx)+ return TemplateResponse(+ request, 'dashboard/product/product_form.html', ctx)@staff_member_required@@ -62,7 +63,8 @@ def product_edit(request, pk):'product': product, 'stock_delete_form': stock_delete_form,'stock_items': stock_items, 'variants': variants,'variants_delete_form': variants_delete_form}- return TemplateResponse(request, 'dashboard/product/product_form.html', ctx)+ return TemplateResponse(+ request, 'dashboard/product/product_form.html', ctx)@staff_member_required@@ -193,7 +195,8 @@ def variant_edit(request, product_pk, variant_pk=None):return redirect(success_url)ctx = {'attribute_form': attribute_form, 'form': form, 'product': product,'variant': variant}- return TemplateResponse(request, 'dashboard/product/variant_form.html', ctx)+ return TemplateResponse(+ request, 'dashboard/product/variant_form.html', ctx)@staff_member_required@@ -262,7 +265,8 @@ def attribute_delete(request, pk):attribute = get_object_or_404(ProductAttribute, pk=pk)if request.method == 'POST':attribute.delete()- messages.success(request, _('Deleted attribute %s' % attribute.display))+ messages.success(+ request, _('Deleted attribute %s') % (attribute.display,))return redirect('dashboard:product-attributes')ctx = {'attribute': attribute}return TemplateResponse(diff --git a/saleor/dashboard/product/widgets.py b/saleor/dashboard/product/widgets.pyindex fc462ace16..1122a8d2f0 100644--- a/saleor/dashboard/product/widgets.py+++ b/saleor/dashboard/product/widgets.py@@ -19,8 +19,7 @@ class ImagePreviewFileInput(ClearableFileInputWithImagePreview):class ImagePreviewWidget(SizedImageCenterpointWidgetMixIn, MultiWidget):-def __init__(self, attrs=None):widgets = (ImagePreviewFileInput(attrs={'class': 'file-chooser'}),HiddenInput(attrs={'class': 'ppoi-input'}))- super(ImagePreviewWidget, self).__init__(widgets, attrs)\ No newline at end of file+ super(ImagePreviewWidget, self).__init__(widgets, attrs)diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex 48daf336bd..1848a5bafb 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -57,12 +57,14 @@ def index(request):payments = Payment.objects.filter(status='preauth').order_by('-created')payments = payments.select_related('order', 'order__user')low_stock = get_low_stock_products()- ctx = {'preauthorized_payments': payments, 'orders_to_ship': orders_to_ship,+ ctx = {'preauthorized_payments': payments,+ 'orders_to_ship': orders_to_ship,'low_stock': low_stock}return TemplateResponse(request, 'dashboard/index.html', ctx)def get_low_stock_products():threshold = getattr(settings, 'LOW_STOCK_THRESHOLD', 10)- products = Product.objects.annotate(total_stock=Sum('variants__stock__quantity'))+ products = Product.objects.annotate(+ total_stock=Sum('variants__stock__quantity'))return products.filter(Q(total_stock__lte=threshold)).distinct()diff --git a/saleor/order/forms.py b/saleor/order/forms.pyindex ec928521cd..8414e1a3e0 100644--- a/saleor/order/forms.py+++ b/saleor/order/forms.py@@ -6,13 +6,12 @@ from .models import Paymentclass PaymentMethodsForm(forms.Form):-- method = forms.ChoiceField(choices=settings.CHECKOUT_PAYMENT_CHOICES, widget=forms.RadioSelect,- initial=settings.CHECKOUT_PAYMENT_CHOICES[0][0])+ method = forms.ChoiceField(+ choices=settings.CHECKOUT_PAYMENT_CHOICES, widget=forms.RadioSelect,+ initial=settings.CHECKOUT_PAYMENT_CHOICES[0][0])class PaymentDeleteForm(forms.Form):-payment_id = forms.IntegerField(widget=forms.HiddenInput())def __init__(self, *args, **kwargs):diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 184cee9487..bb43ddb9c9 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -73,7 +73,6 @@ class Order(models.Model, ItemSet):currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,blank=True, null=True)-class Meta:ordering = ('-last_status_change',)@@ -379,7 +378,7 @@ class Payment(BasePayment):quantity=item.quantity,price=item.unit_price_gross.quantize(Decimal('0.01')),currency=settings.DEFAULT_CURRENCY)- for item in self.order.get_items()]+ for item in self.order.get_items()]return itemsdef get_total_price(self):@@ -393,7 +392,6 @@ class Payment(BasePayment):ordering = ('-pk',)-@python_2_unicode_compatibleclass OrderHistoryEntry(models.Model):date = models.DateTimeField(diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 2c12616eff..50d283a556 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -39,9 +39,9 @@ def order_status_change(sender, instance, **kwargs):def get_ip(request):- ip = request.META.get("HTTP_X_FORWARDED_FOR", None)+ ip = request.META.get('HTTP_X_FORWARDED_FOR', None)if ip:- ip = ip.split(", ")[0]+ ip = ip.split(', ')[0]else:- ip = request.META.get("REMOTE_ADDR", "")+ ip = request.META.get('REMOTE_ADDR', '')return ipdiff --git a/saleor/order/views.py b/saleor/order/views.pyindex 00ef306305..f905d90934 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -75,11 +75,11 @@ def start_payment(request, order, variant):'billing_postcode': billing.postal_code,'billing_country_code': billing.country,'billing_email': order.get_user_email(),- 'description': _('Order %(order_number)s' % {- 'order_number': order}),+ 'description': _('Order %(order_number)s') % {+ 'order_number': order},'billing_country_area': billing.country_area,'customer_ip_address': get_ip(request)}- if not variant in [v for v, n in settings.CHECKOUT_PAYMENT_CHOICES]:+ if variant not in [v for v, n in settings.CHECKOUT_PAYMENT_CHOICES]:raise Http404('%r is not a valid payment variant' % (variant,))with transaction.atomic():order.change_status('payment-pending')diff --git a/saleor/product/admin.py b/saleor/product/admin.pyindex b7ab4146c2..b6556cc8b4 100644--- a/saleor/product/admin.py+++ b/saleor/product/admin.py@@ -15,4 +15,4 @@ class ProductCollectionAdmin(admin.ModelAdmin):admin.site.register(Category, MPTTModelAdmin)-admin.site.register(FixedProductDiscount)\ No newline at end of file+admin.site.register(FixedProductDiscount)diff --git a/saleor/product/forms.py b/saleor/product/forms.pyindex 9b01818245..286c1ecca3 100644--- a/saleor/product/forms.py+++ b/saleor/product/forms.py@@ -42,7 +42,8 @@ class ProductForm(AddToCartForm):class ProductVariantInline(forms.models.BaseInlineFormSet):- error_no_items = pgettext_lazy('Product admin error', 'You have to create at least one variant')+ error_no_items = pgettext_lazy(+ 'Product admin error', 'You have to create at least one variant')def clean(self):count = 0@@ -54,7 +55,8 @@ class ProductVariantInline(forms.models.BaseInlineFormSet):class ImageInline(ProductVariantInline):- error_no_items = pgettext_lazy('Product admin error', 'You have to add at least one image')+ error_no_items = pgettext_lazy(+ 'Product admin error', 'You have to add at least one image')def get_form_class_for_product(product):diff --git a/saleor/product/lookups.py b/saleor/product/lookups.pyindex 9c09c7044b..fbc8c79be3 100644--- a/saleor/product/lookups.py+++ b/saleor/product/lookups.py@@ -8,24 +8,20 @@ from .models import Productclass CollectionLookup(LookupBase):-def get_query(self, request, term):products = Product.objects.filter(collection__isnull=False,collection__istartswith=term)products = products.select_subclasses()qs = products.values('collection').annotate(- products=Count('collection')- ).order_by('-products')+ products=Count('collection')).order_by('-products')return qsdef get_item_value(self, item):return item['collection']def get_item_label(self, item):- collections = "{collection} ({products} products)".format(- **item- )+ collections = '{collection} ({products} products)'.format(**item)return collections-registry.register(CollectionLookup)\ No newline at end of file+registry.register(CollectionLookup)diff --git a/saleor/product/models/base.py b/saleor/product/models/base.pyindex 14d9046efd..f3d106767c 100644--- a/saleor/product/models/base.py+++ b/saleor/product/models/base.py@@ -46,8 +46,9 @@ class Category(MPTTModel):return self.namedef get_absolute_url(self):- return reverse('product:category', kwargs={'path': self.get_full_path(),- 'category_id': self.id})+ return reverse('product:category',+ kwargs={'path': self.get_full_path(),+ 'category_id': self.id})def get_full_path(self):if not self.parent_id:@@ -117,9 +118,6 @@ class Product(models.Model, ItemRange):def get_slug(self):return slugify(smart_text(unidecode(self.name)))- def get_formatted_price(self, price):- return "{0} {1}".format(price.gross, price.currency)-def get_price_per_item(self, item, discounts=None, **kwargs):price = self.priceif price and discounts:@@ -129,20 +127,6 @@ class Product(models.Model, ItemRange):price += modifierreturn price- def admin_get_price_min(self):- price = self.get_price_range().min_price- return self.get_formatted_price(price)-- admin_get_price_min.short_description = pgettext_lazy(- 'Product admin page', 'Minimum price')-- def admin_get_price_max(self):- price = self.get_price_range().max_price- return self.get_formatted_price(price)-- admin_get_price_max.short_description = pgettext_lazy(- 'Product admin page', 'Maximum price')-def is_in_stock(self):return any(variant.is_in_stock() for variant in self)@@ -158,7 +142,8 @@ class ProductVariant(models.Model, Item):sku = models.CharField(pgettext_lazy('Variant field', 'SKU'), max_length=32, unique=True)name = models.CharField(- pgettext_lazy('Variant field', 'variant name'), max_length=100, blank=True)+ pgettext_lazy('Variant field', 'variant name'), max_length=100,+ blank=True)price_override = PriceField(pgettext_lazy('Variant field', 'price override'),currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,@@ -216,7 +201,8 @@ class ProductVariant(models.Model, Item):return Truedef is_in_stock(self):- return any([stock_item.quantity > 0 for stock_item in self.stock.all()])+ return any(+ [stock_item.quantity > 0 for stock_item in self.stock.all()])def get_attribute(self, pk):return self.attributes.get(str(pk))@@ -267,7 +253,7 @@ class Stock(models.Model):unique_together = ('variant', 'location')def __str__(self):- return "%s - %s" % (self.variant.name, self.location)+ return '%s - %s' % (self.variant.name, self.location)@python_2_unicode_compatiblediff --git a/saleor/product/models/images.py b/saleor/product/models/images.pyindex e2085e5b0d..6621abbec9 100644--- a/saleor/product/models/images.py+++ b/saleor/product/models/images.py@@ -22,7 +22,8 @@ class ProductImage(models.Model):upload_to='products', ppoi_field='ppoi', blank=False)ppoi = PPOIField()alt = models.CharField(- pgettext_lazy('Product image field', 'short description'), max_length=128, blank=True)+ pgettext_lazy('Product image field', 'short description'),+ max_length=128, blank=True)order = models.PositiveIntegerField(editable=False)objects = ImageManager()@@ -36,11 +37,13 @@ class ProductImage(models.Model):def save(self, *args, **kwargs):if self.order is None:- c = self.get_ordering_queryset().aggregate(Max('order')).get('order__max')- self.order = 0 if c is None else c + 1+ qs = self.get_ordering_queryset()+ existing_max = qs.aggregate(Max('order'))+ existing_max = existing_max.get('order__max')+ self.order = 0 if existing_max is None else existing_max + 1super(ProductImage, self).save(*args, **kwargs)def delete(self, *args, **kwargs):qs = self.get_ordering_queryset()- qs.filter(order__gt=self.order).update(order=F('order')-1)+ qs.filter(order__gt=self.order).update(order=F('order') - 1)super(ProductImage, self).delete(*args, **kwargs)diff --git a/saleor/product/templatetags/price_ranges.py b/saleor/product/templatetags/price_ranges.pyindex 25d7c0d2fa..67c4c5853d 100644--- a/saleor/product/templatetags/price_ranges.py+++ b/saleor/product/templatetags/price_ranges.py@@ -2,6 +2,7 @@ from django import templateregister = template.Library()+@register.inclusion_tag('product/_price_range.html')def price_range(price_range):- return {'price_range': price_range}\ No newline at end of file+ return {'price_range': price_range}diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 4e5c082b6c..4bcd8cfcd0 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -2,10 +2,8 @@ from __future__ import unicode_literalsfrom django.http import HttpResponsePermanentRedirectfrom django.conf import settings-from django.contrib import messagesfrom django.shortcuts import get_object_or_404, redirectfrom django.template.response import TemplateResponse-from django.utils.translation import ugettext as _from .forms import get_form_class_for_productfrom .models import Product, Category@@ -44,10 +42,12 @@ def category_index(request, path, category_id):return redirect('product:category', permanent=True, path=actual_path,category_id=category_id)products = category.products.get_available_products().select_subclasses()- products = products.prefetch_related('images', 'variants', 'variants__stock')+ products = products.prefetch_related(+ 'images', 'variants', 'variants__stock')products = get_paginator_items(products, settings.PAGINATE_BY, request.GET.get('page'))return TemplateResponse(request, 'category/index.html',{'products': products, 'category': category,- 'children_categories': children_categories, 'breadcrumbs': breadcrumbs})+ 'children_categories': children_categories,+ 'breadcrumbs': breadcrumbs})diff --git a/saleor/registration/forms.py b/saleor/registration/forms.pyindex b8cab36811..7a29e1158d 100644--- a/saleor/registration/forms.py+++ b/saleor/registration/forms.py@@ -32,7 +32,7 @@ class SetOrRemovePasswordForm(SetPasswordForm):def __init__(self, *args, **kwargs):super(SetOrRemovePasswordForm, self).__init__(*args, **kwargs)- if not 'new_password1' in self.data.keys():+ if 'new_password1' not in self.data.keys():self.fields['new_password1'].required = Falseself.fields['new_password2'].required = Falsediff --git a/saleor/registration/models.py b/saleor/registration/models.pyindex 5c5cae8456..a4530ae022 100644--- a/saleor/registration/models.py+++ b/saleor/registration/models.py@@ -10,22 +10,22 @@ from django.utils import timezonenow = timezone.now+def default_valid_date():return now() + timedelta(settings.ACCOUNT_ACTIVATION_DAYS)class ExternalUserData(models.Model):-- user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='external_ids')- service = models.CharField(db_index=True, max_length=255)- username = models.CharField(db_index=True, max_length=255)+ user = models.ForeignKey(+ settings.AUTH_USER_MODEL, related_name='external_ids')+ service = models.CharField(db_index=True, max_length=255)+ username = models.CharField(db_index=True, max_length=255)class Meta:unique_together = [['service', 'username']]class UniqueTokenManager(models.Manager): # this might end up in `utils`-def __init__(self, token_field):self.token_field = token_fieldsuper(UniqueTokenManager, self).__init__()@@ -37,7 +37,6 @@ class UniqueTokenManager(models.Manager): # this might end up in `utils`class AbstractToken(models.Model):-token = models.CharField(max_length=36, unique=True)valid_until = models.DateTimeField(default=default_valid_date)@@ -48,11 +47,11 @@ class AbstractToken(models.Model):class EmailConfirmationRequest(AbstractToken):-email = models.EmailField()def get_authenticated_user(self):- user, _created = get_user_model().objects.get_or_create(email=self.email)+ user, _created = get_user_model().objects.get_or_create(+ email=self.email)return authenticate(user=user)def get_confirmation_url(self):@@ -61,8 +60,8 @@ class EmailConfirmationRequest(AbstractToken):class EmailChangeRequest(AbstractToken):-- user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="email_change_requests")+ user = models.ForeignKey(+ settings.AUTH_USER_MODEL, related_name='email_change_requests')email = models.EmailField() # email address that user is switching todef get_confirmation_url(self):diff --git a/saleor/registration/test_registration.py b/saleor/registration/test_registration.pyindex dd4e78c5a6..fcf108beaf 100644--- a/saleor/registration/test_registration.py+++ b/saleor/registration/test_registration.py@@ -156,7 +156,7 @@ class AccessTokenTestCase(BaseCommunicationTestCase):client = Client(local_host='http://localhost')self.access_token_response.status_code = sentinel.okaccess_token = client.get_access_token(code=sentinel.code)- self.assertEquals(access_token, sentinel.access_token)+ assert access_token == sentinel.access_tokenself.requests_mock.post.assert_called_once_with(sentinel.token_uri,data={'grant_type': 'authorization_code',@@ -193,7 +193,7 @@ class UserInfoTestCase(BaseCommunicationTestCase):self.parse_mock.return_value = sentinel.user_infoself.user_info_response.status_code = sentinel.okuser_info = self.client.get_user_info()- self.assertEquals(user_info, sentinel.user_info)+ assert user_info == sentinel.user_infodef test_user_data_failure(self):"""OAuth2 client reacts well to user info fetch failure"""@@ -220,7 +220,7 @@ class AuthorizerTestCase(TestCase):authorizer = OAuth2RequestAuthorizer(access_token='token')request = Mock(headers={})authorizer(request)- self.assertEquals('Bearer token', request.headers['Authorization'])+ assert request.headers['Authorization'] == 'Bearer token'class CallbackTestCase(TestCase):@@ -240,7 +240,7 @@ class CallbackTestCase(TestCase):self.form = OAuth2CallbackForm(service=sentinel.service,local_host=sentinel.local_host,data={'code': 'test_code'})- self.assertTrue(self.form.is_valid(), self.form.errors)+ assert self.form.is_valid()@patch('saleor.registration.forms.ExternalUserData')@patch('saleor.registration.forms.User')@@ -251,13 +251,12 @@ class CallbackTestCase(TestCase):user = self.form.get_authenticated_user()- self.assertEquals(self.authenticate_mock.mock_calls,- [call(service=sentinel.service,- username=sentinel.id),- call(user=sentinel.user)])+ assert self.authenticate_mock.mock_calls == [+ call(service=sentinel.service, username=sentinel.id),+ call(user=sentinel.user)]external_data_mock.objects.create.assert_called_once_with(service=sentinel.service, username=sentinel.id, user=sentinel.user)- self.assertEquals(user, sentinel.authed_user)+ assert user == sentinel.authed_userdef test_existing_user(self):"""OAuth2 recognizes existing user via external data credentials"""@@ -265,7 +264,7 @@ class CallbackTestCase(TestCase):user = self.form.get_authenticated_user()- self.assertEquals(user, sentinel.authed_user)+ assert user == sentinel.authed_userself.authenticate_mock.assert_called_once_with(service=sentinel.service, username=sentinel.id)@@ -294,10 +293,10 @@ class EmailChangeTestCase(TestCase):# first user clicks link in his emailresult = change_email(request, token_object.token)- self.assertEquals(result.status_code, 302)+ assert result.status_code == 302get.assert_called_once_with(token=token_object.token, valid_until__gte=now())- self.assertFalse(request.user.is_authenticated())+ assert not request.user.is_authenticated()token_object.delete.assert_not_called()@patch('saleor.registration.views.now')@@ -318,16 +317,16 @@ class EmailChangeTestCase(TestCase):# user clicks link in his emailresult = change_email(request, token_object.token)- self.assertEquals(result.status_code, 302)+ assert result.status_code == 302get.assert_called_once_with(token=token_object.token, valid_until__gte=now())# user stays logged in- self.assertTrue(request.user.is_authenticated())+ assert request.user.is_authenticated()# token is deletedtoken_object.delete.assert_called_once_with()user.save.assert_called_once_with()# user email gets changed- self.assertEqual(user.email, token_object.email)+ assert user.email == token_object.emailclass OAuthClientTestCase(TestCase):@@ -339,22 +338,22 @@ class OAuthClientTestCase(TestCase):client = GoogleClient(local_host='http://localhost',client_id=self.fake_client_id,client_secret=self.fake_client_secret)- self.assertEqual(client.client_id, self.fake_client_id)- self.assertEqual(client.client_secret, self.fake_client_secret)+ assert client.client_id == self.fake_client_id+ assert client.client_secret == self.fake_client_secretdef test_google_secrets_fallback(self):client = google_client()- self.assertEqual(client.client_id, settings.GOOGLE_CLIENT_ID)- self.assertEqual(client.client_secret, settings.GOOGLE_CLIENT_SECRET)+ assert client.client_id == settings.GOOGLE_CLIENT_ID+ assert client.client_secret == settings.GOOGLE_CLIENT_SECRETdef test_facebook_secrets_override(self):client = FacebookClient(local_host='http://localhost',client_id=self.fake_client_id,client_secret=self.fake_client_secret)- self.assertEqual(client.client_id, self.fake_client_id)- self.assertEqual(client.client_secret, self.fake_client_secret)+ assert client.client_id == self.fake_client_id+ assert client.client_secret == self.fake_client_secretdef test_facebook_secrets_fallback(self):client = facebook_client()- self.assertEqual(client.client_id, settings.FACEBOOK_APP_ID)- self.assertEqual(client.client_secret, settings.FACEBOOK_SECRET)+ assert client.client_id == settings.FACEBOOK_APP_ID+ assert client.client_secret == settings.FACEBOOK_SECRETdiff --git a/saleor/registration/urls.py b/saleor/registration/urls.pyindex 9a44d83a7e..0348409814 100644--- a/saleor/registration/urls.py+++ b/saleor/registration/urls.py@@ -18,5 +18,4 @@ urlpatterns = [url(r'^request_email_change/$', views.request_email_change,name='request_email_change'),url(r'^change_email/%s/$' % (TOKEN_PATTERN,), views.change_email,- name='change_email')-]\ No newline at end of file+ name='change_email')]diff --git a/saleor/registration/views.py b/saleor/registration/views.pyindex 77f4f83214..a719f9c4b0 100644--- a/saleor/registration/views.py+++ b/saleor/registration/views.py@@ -119,7 +119,7 @@ def change_email(request, token):try:email_change_request = EmailChangeRequest.objects.get(token=token, valid_until__gte=now())- # TODO: cronjob (celery task) to delete stale tokens+ # TODO: cronjob (celery task) to delete stale tokensexcept EmailChangeRequest.DoesNotExist:return TemplateResponse(request, 'registration/invalid_token.html')diff --git a/saleor/settings.py b/saleor/settings.pyindex 14d2d48483..4e7ee85e3a 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -25,7 +25,8 @@ ADMINS = (MANAGERS = ADMINSINTERNAL_IPS = os.environ.get('INTERNAL_IPS', '127.0.0.1').split()-CACHE_URL = os.environ.get('CACHE_URL', os.environ.get('REDIS_URL', 'locmem://'))+CACHE_URL = os.environ.get('CACHE_URL',+ os.environ.get('REDIS_URL', 'locmem://'))CACHES = {'default': django_cache_url.parse(CACHE_URL)}SQLITE_DB_URL = 'sqlite:///' + os.path.join(PROJECT_ROOT, 'dev.sqlite')diff --git a/saleor/userprofile/views.py b/saleor/userprofile/views.pyindex 5b2b53c7b1..9e3086927f 100755--- a/saleor/userprofile/views.py+++ b/saleor/userprofile/views.py@@ -8,7 +8,6 @@ from django.views.decorators.http import require_POSTfrom django.utils.translation import ugettext as _from .forms import AddressForm-from .models import User@login_requireddiff --git a/saleor/wsgi/__init__.py b/saleor/wsgi/__init__.pyindex 69d2868f85..8dbb525aac 100644--- a/saleor/wsgi/__init__.py+++ b/saleor/wsgi/__init__.py@@ -15,7 +15,7 @@ framework."""import os-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')# This application object is used by any WSGI server configured to use this# file. This includes Django's development server, if the WSGI_APPLICATIONdiff --git a/saleor/wsgi/static.py b/saleor/wsgi/static.pyindex 460ac336d3..c613e714f7 100644--- a/saleor/wsgi/static.py+++ b/saleor/wsgi/static.py@@ -1,6 +1,6 @@import os-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')from django.core.wsgi import get_wsgi_applicationfrom whitenoise.django import DjangoWhiteNoisediff --git a/setup.py b/setup.pyindex 0ab2180cb1..b6e67c6c14 100755--- a/setup.py+++ b/setup.py@@ -8,7 +8,7 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')class PyTest(TestCommand):- user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]+ user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]test_args = []def initialize_options(self):@@ -21,7 +21,7 @@ class PyTest(TestCommand):self.test_suite = Truedef run_tests(self):- #import here, cause outside the eggs aren't loaded+ # import here, cause outside the eggs aren't loadedimport pytesterrno = pytest.main(self.pytest_args)sys.exit(errno)diff --git a/tox.ini b/tox.iniindex 7bd3719fb4..cec7aad6e5 100644--- a/tox.ini+++ b/tox.ini@@ -18,4 +18,4 @@ testpaths = saleorDJANGO_SETTINGS_MODULE = saleor.test_settings[flake8]-ignore = H101,H238,H301+ignore = H101,H238,H301,H306