You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.3 KiB

import datetime
import os
from db import Product, Variant
from teespring import Teespring
class Sync(object):
@staticmethod
def _get(d, *keys, default=None):
try:
result = None
for key in keys:
if result:
if isinstance(result, list):
result = result[key]
else:
result = result.get(key, default)
else:
result = d.get(key, default)
return result
except (KeyError, IndexError):
return default
@classmethod
def sync_products(cls, app, db):
app.logger.info('Starting synchronization of products')
with app.app_context():
teespring = Teespring(os.getenv('TEESPRING_STORE_NAME'))
for prod in teespring.fetch_products():
id = cls._get(prod, 'id')
if not id:
continue
q = db.session.query(Product).filter(Product.id == id)
product = q.first()
if not product:
product = Product(id=id)
product.name = cls._get(prod, 'name')
product.product_name = cls._get(prod, 'product_name')
product.price = cls._get(prod, 'price')
product.time_left = cls._get(prod, 'time_left')
product.days_left = cls._get(prod, 'days_left')
product.url = cls._get(prod, 'url')
product.image_url = cls._get(prod, 'image_url')
for var in cls._get(prod, 'variants'):
color_id = cls._get(var, 'color_id')
q = db.session.query(Variant).filter(
Variant.id == color_id,
Variant.product_id == id)
variant = q.first()
if not variant:
variant = Variant(id=color_id)
variant.front_url = cls._get(var, 'front_url')
variant.back_url = cls._get(var, 'back_url')
variant.color = cls._get(var, 'color_value')
product.variants.append(variant)
db.session.add(product)
db.session.commit()
app.logger.info('Synchronization of products completed')