terom@50: """ terom@50: Miscellaneous things terom@50: """ terom@50: terom@72: import datetime, calendar, pytz terom@50: terom@51: from qmsk.web.urltree import URLType terom@51: terom@51: class URLChannelName (URLType) : terom@50: """ terom@51: Handle LogChannel names in URLs. Deals with instances of LogChannel terom@50: """ terom@50: terom@51: def __init__ (self, channels) : terom@50: """ terom@51: Use the given { name -> LogChannel } dict terom@51: """ terom@51: terom@51: self.channels = channels terom@51: terom@51: def parse (self, chan_name) : terom@51: """ terom@51: chan_name -> LogChannel terom@51: """ terom@51: terom@51: return self.channels[chan_name] terom@51: terom@51: def build (self, chan) : terom@51: """ terom@51: LogChannel -> chan_name terom@51: """ terom@51: terom@51: return chan.id terom@51: terom@51: class URLDateType (URLType) : terom@51: """ terom@51: Handle dates in URLs as naive datetime objects (with indeterminate time info) terom@51: """ terom@51: terom@51: def __init__ (self, date_fmt="%Y-%m-%d") : terom@51: """ terom@51: Format/parse dates using the given format terom@51: """ terom@51: terom@51: self.date_fmt = date_fmt terom@51: terom@51: def parse (self, date_str) : terom@51: """ terom@51: date_str -> naive datetime.datetime terom@50: """ terom@50: terom@51: return datetime.datetime.strptime(date_str, self.date_fmt) terom@50: terom@51: def build (self, date) : terom@51: """ terom@51: datetime.date -> date_str terom@51: """ terom@50: terom@51: return date.strftime(self.date_fmt) terom@50: terom@72: class URLTimestampType (URLType) : terom@72: """ terom@72: Handles an integer UNIX timestamp as an UTC datetime terom@72: """ terom@72: terom@72: def parse (self, timestamp_str) : terom@72: """ terom@72: timestamp_str -> pytz.utc datetime.datetime terom@72: """ terom@72: terom@72: return datetime.datetime.utcfromtimestamp(int(timestamp_str)).replace(tzinfo=pytz.utc) terom@72: terom@72: def build (self, dtz) : terom@72: """ terom@72: pytz.utc datetime.datetime -> timestamp_str terom@72: """ terom@72: terom@72: return str(calendar.timegm(dtz.utctimetuple())) terom@72: