Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Refactored integrations into data_feeds

Krzysztof Wolski405162deae71
diff --git a/saleor/integrations/__init__.py b/saleor/data_feeds/__init__.py
similarity index 100%
rename from saleor/integrations/__init__.py
rename to saleor/data_feeds/__init__.py
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
new file mode 100644
index 0000000000..de5318f8b0
--- /dev/null
+++ b/saleor/data_feeds/google_merchant.py
@@ -0,0 +1,219 @@
+from __future__ import unicode_literals
+
+import gzip
+import csv
+from os import path
+
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.contrib.syndication.views import add_domain
+from django.core.files.storage import default_storage
+
+from ..discount.models import Sale
+from ..product.models import ProductVariant, Category
+
+CATEGORY_SEPARATOR = ' > '
+
+FILE_PATH = path.join(settings.INTEGRATIONS_DIR, 'saleor-feed.csv.gz')
+FILE_URL = default_storage.url(FILE_PATH)
+COMPRESSION = False
+
+ATTRIBUTES = ['id', 'title', 'product_type', 'google_product_category',
+ 'link', 'image_link', 'condition', 'availability',
+ 'price', 'tax', 'shipping', 'sale_price',
+ 'mpn', 'brand', 'item_group_id', 'gender', 'age_group',
+ 'color', 'size', 'description']
+
+
+def get_feed_items():
+ return ProductVariant.objects.all().select_related(
+ 'product'
+ ).prefetch_related(
+ 'images', 'stock',
+ 'product__attributes', 'product__categories', 'product__images',
+ )
+
+
+def item_id(item):
+ return item.sku
+
+
+def item_mpn(item):
+ return str(item.sku)
+
+
+def item_guid(item):
+ return item.sku
+
+
+def item_link(item, current_site):
+ return add_domain(current_site.domain,
+ item.get_absolute_url(),
+ not settings.DEBUG)
+
+
+def item_title(item):
+ return item.display_product()
+
+
+def item_description(item):
+ return item.product.description[:100]
+
+
+def item_condition(item):
+ """
+ Allowed values: new, refurbished, or used
+ Read more:
+ https://support.google.com/merchants/answer/6324469
+ """
+ return 'new'
+
+
+def item_brand(item):
+ """
+ This field is required.
+ Read more:
+ https://support.google.com/merchants/answer/6324351?hl=en&ref_topic=6324338
+ """
+ return 'Saleor'
+
+
+def item_tax(item, discounts):
+ """
+ For some countries you need to set tax info
+ Read more:
+ https://support.google.com/merchants/answer/6324454
+ """
+ price = item.get_price_per_item(discounts=discounts)
+ tax = price.gross - price.gross
+ return 'US::%s:y' % tax
+
+
+def item_group_id(item):
+ return str(item.product.pk)
+
+
+def item_image_link(item, current_site):
+ image = item.get_first_image()
+ if image:
+ return add_domain(current_site.domain, image.url, False)
+ else:
+ return None
+
+
+def item_availability(item):
+ if item.get_stock_quantity():
+ return 'in stock'
+ else:
+ return 'out of stock'
+
+
+def item_shipping(item):
+ """
+ You can set one shipping cost in feed settings or precise shipping cost
+ for every item.
+ Read more:
+ https://support.google.com/merchants/answer/7050921
+ """
+ return ''
+
+
+def item_google_product_category(item, category_paths):
+ """
+ To have your categories accepted, please use names accepted by Google or
+ write custom function which maps your category names into to Google codes.
+ Read more:
+ https://support.google.com/merchants/answer/6324436
+ """
+ category = item.product.get_first_category()
+ if category:
+ if category.pk in category_paths:
+ return category_paths[category.pk]
+ ancestors = [ancestor.name for ancestor
+ in list(category.get_ancestors())]
+ category_path = CATEGORY_SEPARATOR.join(ancestors + [category.name])
+ category_paths[category.pk] = category_path
+ return category_path
+ else:
+ return ''
+
+
+def item_price(item):
+ price = item.get_price_per_item(discounts=None)
+ return '%s %s' % (price.gross, price.currency)
+
+
+def item_sale_price(item, discounts):
+ sale_price = item.get_price_per_item(discounts=discounts)
+ return '%s %s' % (sale_price.gross, sale_price.currency)
+
+
+def item_attributes(item, categories, category_paths, current_site,
+ discounts):
+ product_data = {
+ 'id': item_id(item),
+ 'title': item_title(item),
+ 'description': item_description(item),
+ 'condition': item_condition(item),
+ 'mpn': item_mpn(item),
+ 'item_group_id': item_group_id(item),
+ 'availability': item_availability(item),
+ 'google_product_category': item_google_product_category(
+ item, category_paths),
+ 'link': item_link(item, current_site),
+ 'shipping': item_shipping(item),
+ 'brand': item_brand(item)
+ }
+
+ image_link = item_image_link(item, current_site)
+ if image_link:
+ product_data['image_link'] = image_link
+
+ price = item_price(item)
+ product_data['price'] = price
+ sale_price = item_sale_price(item, discounts)
+ if sale_price != price:
+ product_data['sale_price'] = sale_price
+
+ tax = item_tax(item, discounts)
+ if tax:
+ product_data['tax'] = tax
+
+ shipping = item_shipping(item)
+ if shipping:
+ product_data['shipping'] = shipping
+
+ brand = item_brand(item)
+ if brand:
+ product_data['brand'] = brand
+
+ return product_data
+
+
+def update_feed():
+ with default_storage.open(FILE_PATH, 'wb') as output_file:
+ if COMPRESSION:
+ try:
+ output = gzip.open(output_file, 'wt')
+ except TypeError:
+ output = gzip.GzipFile(fileobj=output_file, mode='w')
+ else:
+ output = output_file
+
+ writer = csv.DictWriter(output, ATTRIBUTES,
+ dialect=csv.excel_tab)
+ writer.writeheader()
+
+ categories = Category.objects.all()
+ discounts = Sale.objects.all().prefetch_related('products',
+ 'categories')
+ category_paths = {}
+ current_site = Site.objects.get_current()
+
+ for item in get_feed_items():
+ writer.writerow(
+ item_attributes(item, categories, category_paths,
+ current_site, discounts))
+
+ if COMPRESSION:
+ output.close()
diff --git a/saleor/data_feeds/management/__init__.py b/saleor/data_feeds/management/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/data_feeds/management/commands/__init__.py b/saleor/data_feeds/management/commands/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/data_feeds/management/commands/update_feeds.py b/saleor/data_feeds/management/commands/update_feeds.py
new file mode 100644
index 0000000000..8fda5e78cf
--- /dev/null
+++ b/saleor/data_feeds/management/commands/update_feeds.py
@@ -0,0 +1,12 @@
+from __future__ import unicode_literals
+
+from django.core.management import BaseCommand
+
+from ...google_merchant import update_feed
+
+
+class Command(BaseCommand):
+ help = 'Update Google merchant feed'
+
+ def handle(self, *args, **options):
+ update_feed()
diff --git a/saleor/data_feeds/urls.py b/saleor/data_feeds/urls.py
new file mode 100644
index 0000000000..b655c08be4
--- /dev/null
+++ b/saleor/data_feeds/urls.py
@@ -0,0 +1,9 @@
+from django.conf.urls import url
+from django.views.generic.base import RedirectView
+
+from .google_merchant import FILE_URL
+
+urlpatterns = [
+ url(r'saleor-feed/$',
+ RedirectView.as_view(url=FILE_URL), name='saleor-feed'),
+]
diff --git a/saleor/integrations/feeds.py b/saleor/integrations/feeds.py
deleted file mode 100644
index f43b079eab..0000000000
--- a/saleor/integrations/feeds.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from __future__ import unicode_literals
-
-from os import path
-
-from django.conf import settings
-from django.contrib.sites.models import Site
-from django.contrib.syndication.views import add_domain
-from django.core.files.storage import default_storage
-
-from ..discount.models import Sale
-from ..product.models import ProductVariant, Category
-
-CATEGORY_SEPARATOR = ' > '
-
-
-class GoogleMerchant(object):
- """
- Basic Google feed class. To adjust feed to your needs inherit from
- this class.
-
- Depending on target country and law changes required fields can change,
- please validate your feed at Google Merchant dashboard and override
- missing methods.
-
- Google feeds dashboard:
- https://merchants.google.com/mc/feeds/dashboard
-
- For more info check Google support pages:
- https://support.google.com/merchants/answer/7052112?visit_id=1-636148270257062854-1147518273&rd=1
- """
- file_path = path.join(settings.INTEGRATIONS_DIR, 'google-merchant.csv.gz')
- file_url = default_storage.url(file_path)
- compression = True
- attributes = ['id', 'title', 'product_type', 'google_product_category',
- 'link', 'image_link', 'condition', 'availability',
- 'price', 'tax', 'shipping', 'sale_price',
- 'mpn', 'brand', 'item_group_id', 'gender', 'age_group',
- 'color', 'size', 'description']
-
- def __init__(self):
- self.categories = Category.objects.all()
- self.discounts = Sale.objects.all().prefetch_related(
- 'products', 'categories')
- self.category_paths = {}
- self.current_site = Site.objects.get_current()
-
- def get_full_category_name_path(self, category):
- if category.pk in self.category_paths:
- return self.category_paths[category.pk]
- ret = CATEGORY_SEPARATOR.join(
- [category.name for category
- in list(category.get_ancestors()) + [category]])
- self.category_paths[category.pk] = ret
- return ret
-
- def items(self):
- self.discounts = None
- return ProductVariant.objects.all().select_related(
- 'product'
- ).prefetch_related(
- 'images', 'stock',
- 'product__attributes', 'product__categories', 'product__images',
- )
-
- def item_id(self, item):
- return item.sku
-
- def item_mpn(self, item):
- return str(item.sku)
-
- def item_guid(self, item):
- return item.sku
-
- def item_link(self, item):
- return add_domain(self.current_site.domain,
- item.get_absolute_url(),
- not settings.DEBUG)
-
- def item_title(self, item):
- return item.display_product()
-
- def item_description(self, item):
- return item.product.description[:100]
-
- def item_condition(self, item):
- """
- Allowed values: new, refurbished, or used
- Read more:
- https://support.google.com/merchants/answer/6324469
- """
- return 'new'
-
- def item_brand(self, item):
- """
- This field is required.
- Read more:
- https://support.google.com/merchants/answer/6324351?hl=en&ref_topic=6324338
- """
- return None
-
- def item_tax(self, item):
- """
- For some countries you need to set tax info
- Read more:
- https://support.google.com/merchants/answer/6324454
- """
- return None
-
- def item_group_id(self, item):
- return str(item.product.pk)
-
- def item_image_link(self, item):
- image = item.get_first_image()
- if image:
- return add_domain(self.current_site.domain, image.url, False)
- else:
- return None
-
- def item_availability(self, item):
- if item.get_stock_quantity():
- return 'in stock'
- else:
- return 'out of stock'
-
- def item_shipping(self, item):
- """
- You can set one shipping cost in feed settings or precise shipping cost for every item.
- Read more:
- https://support.google.com/merchants/answer/7050921
- """
- return ''
-
- def item_google_product_category(self, item):
- """
- To have your categories accepted, please use names accepted by Google or
- write custom function which maps your category names into to Google codes.
- Read more:
- https://support.google.com/merchants/answer/6324436
- """
- category = item.product.get_first_category()
- if category:
- category_path = self.get_full_category_name_path(category)
- return category_path
- else:
- return ''
-
- def item_price(self, item):
- price = item.get_price_per_item(discounts=None)
- return '%s %s' % (price.gross, price.currency)
-
- def item_sale_price(self, item):
- sale_price = item.get_price_per_item(discounts=self.discounts)
- return '%s %s' % (sale_price.gross, sale_price.currency)
-
- def item_attributes(self, item):
- product_data = {
- 'id': self.item_id(item),
- 'title': self.item_title(item),
- 'description': self.item_description(item),
- 'condition': self.item_condition(item),
- 'mpn': self.item_mpn(item),
- 'item_group_id': self.item_group_id(item),
- 'availability': self.item_availability(item),
- 'google_product_category': self.item_google_product_category(item),
- 'link': self.item_link(item),
- 'tax': self.item_tax(item),
- 'shipping': self.item_shipping(item)
- }
-
- image_link = self.item_image_link(item)
- if image_link:
- product_data['image_link'] = image_link
-
- price = self.item_price(item)
- product_data['price'] = price
- sale_price = self.item_sale_price(item)
- if sale_price != price:
- product_data['sale_price'] = sale_price
-
- tax = self.item_tax(item)
- if tax:
- product_data['tax'] = tax
-
- shipping = self.item_shipping(item)
- if shipping:
- product_data['shipping'] = shipping
-
- brand = self.item_brand(item)
- if brand:
- product_data['brand'] = brand
-
- return product_data
-
-
-class SaleorGoogleMerchant(GoogleMerchant):
- """
- Example of using GoogleMerchant.
- """
- file_path = path.join(settings.INTEGRATIONS_DIR, 'saleor-feed.csv.gz')
- file_url = default_storage.url(file_path)
-
- def item_tax(self, item):
- """No taxes on products"""
- price = item.get_price_per_item(discounts=self.discounts)
- tax = price.gross - price.gross
- return 'US::%s:y' % tax
-
- def item_brand(self, item):
- return 'Saleor'
diff --git a/saleor/integrations/management/__init__.py b/saleor/integrations/management/__init__.py
deleted file mode 100644
index 8b13789179..0000000000
--- a/saleor/integrations/management/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/saleor/integrations/management/commands/__init__.py b/saleor/integrations/management/commands/__init__.py
deleted file mode 100644
index 8b13789179..0000000000
--- a/saleor/integrations/management/commands/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/saleor/integrations/management/commands/update_integrations.py b/saleor/integrations/management/commands/update_integrations.py
deleted file mode 100644
index 026d8e360c..0000000000
--- a/saleor/integrations/management/commands/update_integrations.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from __future__ import unicode_literals
-
-from django.core.management import CommandError, BaseCommand
-
-from ...feeds import SaleorGoogleMerchant
-from ... import utils
-
-
-class Command(BaseCommand):
- help = ('Updates integration feeds.'
- 'If feed name not provided, updates all available feeds')
- feed_classes = {'saleor': SaleorGoogleMerchant}
-
- def add_arguments(self, parser):
- parser.add_argument('feed_name', nargs='*', type=str, default=None)
-
- def handle(self, *args, **options):
- feed_names = options.get('feed_name') or self.feed_classes.keys()
- for feed_name in feed_names:
- feed = self.feed_classes.get(feed_name)
- if feed is None:
- raise CommandError('Feed "%s" does not exist' % feed_name)
- utils.update_feed(feed())
diff --git a/saleor/integrations/urls.py b/saleor/integrations/urls.py
deleted file mode 100644
index 28b4167c73..0000000000
--- a/saleor/integrations/urls.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from django.conf.urls import url
-from django.views.generic.base import RedirectView
-
-from .feeds import SaleorGoogleMerchant
-
-urlpatterns = [
- url(r'saleor-feed/$', RedirectView.as_view(url=SaleorGoogleMerchant.file_url),
- name='saleor-feed'),
-]
diff --git a/saleor/integrations/utils.py b/saleor/integrations/utils.py
deleted file mode 100644
index 8addd4b53e..0000000000
--- a/saleor/integrations/utils.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from __future__ import unicode_literals
-
-import gzip
-import csv
-
-from django.core.files.storage import default_storage
-
-
-def update_feed(feed):
- with default_storage.open(feed.file_path, 'wb') as output_file:
- if feed.compression:
- try:
- output = gzip.open(output_file, 'wt')
- except TypeError:
- output = gzip.GzipFile(fileobj=output_file, mode='w')
- else:
- output = output_file
-
- writer = csv.DictWriter(output, feed.attributes,
- dialect=csv.excel_tab)
- writer.writeheader()
- for item in feed.items():
- writer.writerow(feed.item_attributes(item))
-
- if feed.compression:
- output.close()
diff --git a/saleor/settings.py b/saleor/settings.py
index ef4fee9543..d1abf8e044 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -154,6 +154,7 @@ INSTALLED_APPS = [
'saleor.shipping',
'saleor.search',
'saleor.integrations',
+ 'saleor.data_feeds',
# External apps
'versatileimagefield',
diff --git a/saleor/urls.py b/saleor/urls.py
index e4afc5e632..24b864d601 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -13,7 +13,7 @@ from .order.urls import urlpatterns as order_urls
from .product.urls import urlpatterns as product_urls
from .search.urls import urlpatterns as search_urls
from .userprofile.urls import urlpatterns as userprofile_urls
-from .integrations.urls import urlpatterns as integrations_urls
+from .data_feeds.urls import urlpatterns as integrations_urls
from .dashboard.urls import urlpatterns as dashboard_urls
@@ -31,7 +31,7 @@ urlpatterns = [
url(r'^profile/', include(userprofile_urls, namespace='profile')),
url(r'^search/', include(search_urls, namespace='search')),
url(r'^selectable/', include('selectable.urls')),
- url(r'^integrations/', include(integrations_urls, namespace='integrations')),
+ url(r'^data_feeds/', include(integrations_urls, namespace='data_feeds')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
url(r'', include('payments.urls'))
diff --git a/tests/test_data_feeds.py b/tests/test_data_feeds.py
new file mode 100644
index 0000000000..1bda011f2c
--- /dev/null
+++ b/tests/test_data_feeds.py
@@ -0,0 +1,72 @@
+from __future__ import unicode_literals
+
+import csv
+from mock import Mock
+try:
+ from StringIO import StringIO
+except ImportError:
+ from io import StringIO
+
+from django.contrib.sites.models import Site
+
+from saleor.discount.models import Sale
+from saleor.product.models import Category
+from saleor.data_feeds.google_merchant import (get_feed_items,
+ item_attributes,
+ item_google_product_category,
+ update_feed)
+
+
+def test_saleor_feed_items(product_in_stock):
+ valid_variant = product_in_stock.variants.first()
+ items = get_feed_items()
+ assert len(items) == 1
+ categories = Category.objects.all()
+ discounts = []
+ category_paths = {}
+ current_site = Site.objects.get_current()
+ attributes = item_attributes(items[0], categories, category_paths,
+ current_site, discounts)
+ assert attributes.get('mpn') == valid_variant.sku
+ assert attributes.get('availability') == 'in stock'
+
+
+def test_category_formatter(db):
+ main_category = Category(name='Main', slug='main')
+ main_category.save()
+ main_category_item = Mock(
+ product=Mock(get_first_category=lambda: main_category))
+ sub_category = Category(name='Sub', slug='sub', parent=main_category)
+ sub_category.save()
+ sub_category_item = Mock(
+ product=Mock(get_first_category=lambda: sub_category))
+ assert item_google_product_category(
+ main_category_item, {}) == 'Main'
+ assert item_google_product_category(
+ sub_category_item, {}) == 'Main > Sub'
+
+
+def test_feed_updater(product_in_stock, monkeypatch):
+ variant = product_in_stock.variants.first()
+ fake_file = StringIO()
+ fake_file.__exit__ = lambda x, y, z: None
+ fake_file.close = lambda: None
+ fake_file.__enter__ = lambda: fake_file
+ monkeypatch.setattr(
+ 'saleor.data_feeds.google_merchant.default_storage.open',
+ lambda path, mode: fake_file)
+ monkeypatch.setattr(
+ 'saleor.data_feeds.google_merchant.COMPRESSION', False)
+ update_feed()
+ fake_file.seek(0)
+ categories = Category.objects.all()
+ discounts = Sale.objects.all().prefetch_related('products',
+ 'categories')
+ category_paths = {}
+ current_site = Site.objects.get_current()
+ reader = csv.DictReader(fake_file, dialect=csv.excel_tab)
+ for generated_item in reader:
+ attributes = item_attributes(variant, categories, category_paths,
+ current_site, discounts)
+ for key in attributes.keys():
+ assert attributes[key] == generated_item[key]
diff --git a/tests/test_integrations.py b/tests/test_integrations.py
deleted file mode 100644
index 1d5ac3b092..0000000000
--- a/tests/test_integrations.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from __future__ import unicode_literals
-
-import csv
-try:
- from StringIO import StringIO
-except ImportError:
- from io import StringIO
-
-from saleor.product.models import Category
-from saleor.integrations.feeds import SaleorGoogleMerchant
-from saleor.integrations.utils import update_feed
-
-
-def test_saleor_feed_items(product_in_stock):
- valid_variant = product_in_stock.variants.first()
- feed = SaleorGoogleMerchant()
- items = feed.items()
- assert len(items) == 1
- attributes = feed.item_attributes(items[0])
- assert attributes.get('mpn') == valid_variant.sku
- assert attributes.get('availability') == 'in stock'
-
-
-def test_category_formatter(db):
- feed = SaleorGoogleMerchant()
- main_category = Category(name='Main', slug='main')
- main_category.save()
- sub_category = Category(name='Sub', slug='sub', parent=main_category)
- sub_category.save()
- assert feed.get_full_category_name_path(main_category) == 'Main'
- assert feed.get_full_category_name_path(sub_category) == 'Main > Sub'
-
-
-def test_feed_updater(product_in_stock, monkeypatch):
- variant = product_in_stock.variants.first()
- fake_file = StringIO()
- fake_file.__exit__ = lambda x, y, z: None
- fake_file.close = lambda: None
- fake_file.__enter__ = lambda: fake_file
- monkeypatch.setattr('saleor.integrations.utils.default_storage.open',
- lambda path, mode: fake_file)
- feed = SaleorGoogleMerchant()
- feed.compression = False
- update_feed(feed)
- fake_file.seek(0)
- reader = csv.DictReader(fake_file, dialect=csv.excel_tab)
- for generated_item in reader:
- attributes = feed.item_attributes(variant)
- for key in attributes.keys():
- assert attributes[key] == generated_item[key]