added image-grabbing code to woocommerve migration,images still saved locally

This commit is contained in:
Sam
2021-02-22 11:21:19 +00:00
parent ee0150e513
commit 5a1084bf7b
3 changed files with 31 additions and 6 deletions

View File

@@ -52,6 +52,8 @@ INSTALLED_APPS = [
'taggit_serializer',
'tagulous',
'anymail',
'storages',
# local apps
'core',

View File

@@ -5,6 +5,7 @@ from django.conf import settings
from django.core.management.base import BaseCommand
from companies.models import Company
from products.models import Product
from utils.woocommerce import migrate_shop_products
@@ -29,6 +30,9 @@ class Command(BaseCommand):
help = 'Load data from example site https://woo.enreda.coop/ '
def handle(self, *args, **kwargs):
print("Deleting existing Product instances")
Product.objects.all().delete()
print("Migrate data from Enreda WooCommerce...\n")
# find or create company instance
enreda, created = Company.objects.get_or_create(company_name='enreda', web_link=self.url)

View File

@@ -7,8 +7,12 @@ This file holds the functions necesary to:
"""
import logging
from io import BytesIO
from woocommerce import API
import requests
from PIL import Image
from django.core.files import File
from companies.models import Company
from products.models import Product
@@ -42,12 +46,9 @@ def migrate_shop_products(url, key, secret, version="wc/v3"):
company = Company.objects.filter(web_link=url).first()
if not company:
# logging.error(f"Could not find Company with URL: {url}")
# print(f"Could not find Company with URL: {url}")
# return None
# TODO: ELIMINATE THIS AFTER DEBUGGING
company = Company.objects.create(web_link=url)
logging.error(f"Created Company for testing: {url}")
logging.error(f"Could not find Company with URL: {url}")
print(f"Could not find Company with URL: {url}")
return None
# list products
response = wcapi.get('/products/')
@@ -102,6 +103,24 @@ def migrate_shop_products(url, key, secret, version="wc/v3"):
new.save()
except Exception as e:
logging.error(f"Could not create product instance: {str(e)}")
continue
try:
# import ipdb; ipdb.set_trace()
# get image
headers={
"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
}
image_url = product['images'][0]['src']
response = requests.get(image_url, stream=True, headers=headers)
response.raw.decode_content = True
image = Image.open(response.raw)
# save using File object
img_io = BytesIO()
image.save(img_io, format='JPEG')
new.image.save(f"{new.name}-{new.sku}.jpg", File(img_io), save=False)
new.save()
except Exception as e:
logging.error(f"Could not add image to product: {str(e)}")
else:
logging.error(f"{serializer.errors}")
continue