comfy/artel/store/loader.py

90 wiersze
2.6 KiB
Python
Czysty Zwykły widok Historia

2023-07-26 00:00:35 +00:00
import logging
2023-08-10 20:24:48 +00:00
import time
import requests
2023-07-26 00:00:35 +00:00
import pandas as pd
2023-08-15 11:36:11 +00:00
from django.core.files.base import ContentFile
2023-08-10 20:52:22 +00:00
from django.conf import settings
2023-07-26 00:00:35 +00:00
from store.models import (
ProductTemplate,
2023-08-15 11:36:11 +00:00
ProductTemplateParam,
2023-08-15 19:00:16 +00:00
ProductTemplateParamValue,
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-10 20:24:48 +00:00
def _clear(self):
Product.objects.all().delete()
def __init__(self, path, param_names, clear=False):
super().__init__(path)
self.param_names = param_names
if clear:
self._clear()
2023-08-15 11:36:11 +00:00
def _get_images(self, row) -> list[ContentFile]:
2023-08-10 20:24:48 +00:00
url = row["images"]
images = []
2023-08-10 20:52:22 +00:00
response = requests.get(
url+"/preview", stream=True
)
2023-08-10 20:24:48 +00:00
if response.status_code == 200:
data = response.content
image = ContentFile(data, name=row["template"])
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"])
2023-08-15 11:36:11 +00:00
price = float(row["price"].strip("").replace(",", "."))
2023-07-26 00:00:35 +00:00
name = row["name"]
available = bool(row["available"])
params = []
2023-08-10 20:24:48 +00:00
for key in self.param_names:
value = row[key]
2023-08-15 19:00:16 +00:00
param, _ = ProductTemplateParam.objects.get_or_create(key=key, template=template)
param_value, _ = ProductTemplateParamValue.objects.get_or_create(param=param, value=value)
2023-08-10 20:24:48 +00:00
params.append(param_value)
2023-07-26 00:00:35 +00:00
product = Product.objects.get_or_create_by_params(template=template, params=params)
product.price = price
product.name = name
product.available = available
2023-08-15 11:36:11 +00:00
# NOTE - temporary solution
# images = self._get_images(row)
# 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():
2023-08-10 20:24:48 +00:00
time.sleep(5)
2023-07-26 00:00:35 +00:00
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")