utils.py
author Tero Marttila <terom@fixme.fi>
Mon, 09 Feb 2009 23:49:57 +0200
changeset 73 5a7188bf2894
parent 72 5ade0288f2ec
child 89 2dc6de43f317
permissions -rw-r--r--
split defined configuration constants into config, and implement search result pagination
"""
    Miscellaneous things
"""

import datetime, calendar, pytz

from qmsk.web.urltree import URLType

class URLChannelName (URLType) :
    """
        Handle LogChannel names in URLs. Deals with instances of LogChannel
    """

    def __init__ (self, channels) :
        """
            Use the given { name -> LogChannel } dict
        """

        self.channels = channels
    
    def parse (self, chan_name) :
        """
            chan_name -> LogChannel
        """

        return self.channels[chan_name]

    def build (self, chan) :
        """
            LogChannel -> chan_name
        """

        return chan.id

class URLDateType (URLType) :
    """
        Handle dates in URLs as naive datetime objects (with indeterminate time info)
    """

    def __init__ (self, date_fmt) :
        """
            Format/parse dates using the given format
        """

        self.date_fmt = date_fmt
    
    def parse (self, date_str) :
        """
            date_str -> naive datetime.datetime
        """
        
        return datetime.datetime.strptime(date_str, self.date_fmt)
    
    def build (self, date) :
        """
            datetime.date -> date_str
        """

        return date.strftime(self.date_fmt)

class URLTimestampType (URLType) :
    """
        Handles an integer UNIX timestamp as an UTC datetime
    """

    def parse (self, timestamp_str) :
        """
            timestamp_str -> pytz.utc datetime.datetime
        """

        return datetime.datetime.utcfromtimestamp(int(timestamp_str)).replace(tzinfo=pytz.utc)
    
    def build (self, dtz) :
        """
            pytz.utc datetime.datetime -> timestamp_str
        """

        return str(calendar.timegm(dtz.utctimetuple()))