2023-07-26 00:00:35 +00:00
|
|
|
import logging
|
2023-08-03 19:05:54 +00:00
|
|
|
import requests
|
2023-07-26 00:00:35 +00:00
|
|
|
import pandas as pd
|
|
|
|
|
2023-08-03 19:05:54 +00:00
|
|
|
from django.core import files
|
|
|
|
|
2023-07-26 00:00:35 +00:00
|
|
|
from store.models import (
|
|
|
|
ProductTemplate,
|
|
|
|
ProductCategoryParamValue,
|
2023-08-03 19:05:54 +00:00
|
|
|
Product,
|
|
|
|
ProductImage
|
2023-07-26 00:00:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class BaseLoader:
|
|
|
|
def __init__(self, path):
|
|
|
|
self.path = path
|
|
|
|
|
|
|
|
def load_data(self):
|
|
|
|
return pd.read_csv(self.path)
|
2023-08-01 20:41:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TemplateLoader(BaseLoader):
|
|
|
|
...
|
|
|
|
|
2023-07-26 00:00:35 +00:00
|
|
|
|
|
|
|
class ProductLoader(BaseLoader):
|
|
|
|
|
2023-08-03 19:05:54 +00:00
|
|
|
def _get_images(self, row) -> list[files.ContentFile]:
|
2023-08-01 20:41:10 +00:00
|
|
|
urls = row["images"]
|
2023-08-03 19:05:54 +00:00
|
|
|
images = []
|
2023-08-01 20:41:10 +00:00
|
|
|
for url in urls:
|
2023-08-03 19:05:54 +00:00
|
|
|
response = requests.get(url, stream=True)
|
|
|
|
if response.status_code == 200:
|
|
|
|
data = response.raw
|
|
|
|
file_name = url.split("/")[-1]
|
|
|
|
image = files.ContentFile(data, name=file_name)
|
|
|
|
images.append(image)
|
|
|
|
return images
|
2023-08-01 20:41:10 +00:00
|
|
|
|
2023-07-26 00:00:35 +00:00
|
|
|
def _process_row(self, row):
|
|
|
|
template = ProductTemplate.objects.get(code=row["template"])
|
|
|
|
price = float(row["price"])
|
|
|
|
name = row["name"]
|
|
|
|
available = bool(row["available"])
|
|
|
|
params = []
|
|
|
|
for param in row["params"]:
|
|
|
|
key, value = param
|
|
|
|
param = ProductCategoryParamValue.objects.get(param__key=key, value=value)
|
|
|
|
params.append(param)
|
|
|
|
product = Product.objects.get_or_create_by_params(template=template, params=params)
|
|
|
|
product.price = price
|
|
|
|
product.name = name
|
|
|
|
product.available = available
|
2023-08-01 20:41:10 +00:00
|
|
|
|
|
|
|
images = self._get_images(row)
|
2023-08-03 19:05:54 +00:00
|
|
|
for i, image in enumerate(images):
|
|
|
|
ProductImage.objects.create(product=product, image=image, is_main=bool(i==0))
|
2023-07-26 00:00:35 +00:00
|
|
|
product.save()
|
|
|
|
return product
|
|
|
|
|
|
|
|
def process(self):
|
|
|
|
data = self.load_data()
|
|
|
|
products = []
|
|
|
|
for _, row in data.iterrows():
|
|
|
|
try:
|
|
|
|
product = self._process_row(row)
|
|
|
|
except Exception as e:
|
|
|
|
# catch any error and log it, GlitchTip will catch it
|
|
|
|
logger.exception(str(e))
|
|
|
|
else:
|
|
|
|
products.append(product)
|
|
|
|
logger.info(f"Loaded {len(products)} products")
|