def update_stats(self, from_log=None): if from_log is None: from_log = PriceLog.query.filter_by(product=self).order_by(db.desc(PriceLog.fetched_date)).first() self.one_month_change = self._get_change(to_date=date.today() - timedelta(days=30), from_log=from_log) self.three_month_change = self._get_change(to_date=date.today() - timedelta(days=90), from_log=from_log) self.six_month_change = self._get_change(to_date=date.today() - timedelta(days=180), from_log=from_log) self.one_year_change = self._get_change(to_date=date.today() - timedelta(days=365), from_log=from_log) self.updated_date = datetime.utcnow()
def __init__(self, price=None, currency=None, product=None, fetched_date=None): previous_log = PriceLog.query.filter_by(product=product).order_by(db.desc(PriceLog.fetched_date)).limit(1).all() if previous_log: previous_log = previous_log[0] self.change = ((price - previous_log.price) / previous_log.price) * 100 else: self.change = 0 self.price = price self.currency = currency self.product = product if fetched_date: self.fetched_date = fetched_date else: self.fetched_date = datetime.utcnow() # Actualizo los valores. product.update_stats(from_log=self)
def _get_change(self, to_date=None, from_date=None, from_log=None): if from_log is None: if from_date is None: from_log = PriceLog.query.filter_by(product=self).order_by(db.desc(PriceLog.fetched_date)).first() else: from_log = ( PriceLog.query.filter_by(product=self) .filter(PriceLog.fetched_date.between(from_date, from_date + timedelta(days=1))) .first() ) to_log = ( PriceLog.query.filter_by(product=self) .filter(PriceLog.fetched_date.between(to_date, to_date + timedelta(days=1))) .first() ) if to_log is None: to_log = PriceLog.query.filter_by(product=self).order_by(db.asc(PriceLog.fetched_date)).first() if from_log is None or to_log is None: return 0 return (from_log.price - to_log.price) / to_log.price * 100