def getNearestTime(time_query): """Given a datetime object, return the nearest time in the database (in string format), or None if empty.""" # Convert datetime object to string, for lookup in database. tstamp_query = coils.time2string(time_query) # Retrieve image timestamps. try: tstamp_left = db.session.query(mapping.Image.time).\ filter(mapping.Image.time <= tstamp_query).\ order_by(mapping.Image.time.desc()).limit(1) tstamp_left = tstamp_left[0].time delta_left = abs(coils.string2time(tstamp_left) - time_query) except: tstamp_left = None delta_left = dt.timedelta.max try: tstamp_right = db.session.query(mapping.Image.time).\ filter(mapping.Image.time >= tstamp_query).\ order_by(mapping.Image.time).limit(1) tstamp_right = tstamp_right[0].time delta_right = abs(coils.string2time(tstamp_right) - time_query) except: tstamp_right = None delta_right = dt.timedelta.max # The nearest value has the smallest delta from the query. result = tstamp_left if (delta_left < delta_right) else tstamp_right return result
def doTask(self, tstamp): """Write to the database.""" # Add the item. image = mapping.Image(tstamp) self._sess.add(image) # Increment the size. self._sess.query(mapping.Datum).\ filter(mapping.Datum.name=='size').\ update({'value':mapping.Datum.value+1}) # Update latest timestamp. self._sess.query(mapping.Datum).\ filter(mapping.Datum.name=='latest_tstamp').\ update({'value': coils.time2string(tstamp)}) # Commit the transaction. self._sess.commit()
def info(): """Return system information.""" now = dt.datetime.now() now = coils.time2string(now) size = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] latest_tstamp = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='latest_tstamp')[0] latest_url = coils.time2fname( coils.string2time( latest_tstamp.value), full=True) latest_url = 'pics/{}.jpg'.format(latest_url) load_avg = os.getloadavg() return flask.jsonify( server_time=now, db_size=size.value, latest_tstamp=latest_tstamp.value, latest_url=latest_url, load_avg='{:.2f}, {:.2f}, {:.2f}'.format(*load_avg), )
def __init__(self, tstamp): self.value = coils.time2string(tstamp)