139 lines
4.3 KiB
Python
139 lines
4.3 KiB
Python
"""
|
|
This file holds the functions necesary to:
|
|
|
|
- Connect to seller's shop API
|
|
- Load information on seller [??]
|
|
- Load product information
|
|
|
|
"""
|
|
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
|
|
from products.serializers import ProductSerializer
|
|
|
|
|
|
def get_wcapi_instance(url, key, secret, version="wc/v3"):
|
|
wcapi = API(
|
|
url=url,
|
|
consumer_key=key,
|
|
consumer_secret=secret,
|
|
wp_api=True,
|
|
version=version
|
|
)
|
|
return wcapi
|
|
|
|
|
|
def migrate_shop_products(url, key, secret, version="wc/v3"):
|
|
"""Tries to connect to WooCommerce site @ url with given credentials
|
|
|
|
If succesful, returns list of Product instances created
|
|
|
|
"""
|
|
# get wcapi
|
|
wcapi = get_wcapi_instance(url, key, secret, version)
|
|
|
|
consumer_key = 'ck_565539bb25b472b1ff7a209eb157ca11c0a26397'
|
|
consumer_secret = 'cs_9c1690ba5da0dd70f51d61c395628fa14d1a104c'
|
|
|
|
# get company fom url
|
|
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
|
|
|
|
# list products
|
|
response = wcapi.get('/products/')
|
|
if response.status_code == 200:
|
|
products = response.json()
|
|
elif response.status_code == 401:
|
|
logging.error(f"{response.status_code} [{response.url}]: {response.json()}")
|
|
return None
|
|
else:
|
|
logging.error(f"Could not load products from {url}: [{response.status_code}]")
|
|
print(f"Could not load products fom {url}: [{response.status_code}]")
|
|
return None
|
|
|
|
product_fields = [f.name for f in Product._meta.get_fields()]
|
|
counter = 0
|
|
products_created = []
|
|
for product in products:
|
|
instance_data = {'company':company.id}
|
|
# parse the product info
|
|
for key in product:
|
|
if key in product_fields:
|
|
instance_data[key] = product[key]
|
|
# remove unwanted fields
|
|
instance_data.pop('id')
|
|
# extract m2m field data
|
|
tags = instance_data.pop('tags')
|
|
attributes = instance_data.pop('attributes')
|
|
|
|
# create instance with serializer
|
|
'''
|
|
serializer = ProductSerializer(data=instance_data)
|
|
if serializer.is_valid():
|
|
new = serializer.save()
|
|
if tags:
|
|
new.tags.set(tags)
|
|
if attributes:
|
|
new.attributes.set(attributes)
|
|
new.save()
|
|
else:
|
|
logging.error(f"{serializer.errors}")
|
|
continue
|
|
'''
|
|
# alternative method
|
|
serializer = ProductSerializer(data=instance_data)
|
|
if serializer.is_valid():
|
|
try:
|
|
new = Product.objects.create(**serializer.validated_data)
|
|
if tags:
|
|
new.tags.set(tags)
|
|
if attributes:
|
|
new.attributes.set(attributes)
|
|
new.save()
|
|
except Exception as e:
|
|
logging.error(f"Could not create product instance: {str(e)}")
|
|
continue
|
|
try:
|
|
# 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
|
|
|
|
products_created.append(new)
|
|
counter += 1
|
|
logging.info(f"Product {instance_data.get('name')} created")
|
|
print(f"Product {instance_data.get('name')} created")
|
|
|
|
print(f"Products created: {counter}")
|
|
return products_created
|
|
|
|
|
|
|
|
|
|
|