utils.py
author Tero Marttila <terom@fixme.fi>
Wed, 11 Feb 2009 00:33:21 +0200
changeset 89 2dc6de43f317
parent 73 5a7188bf2894
child 95 ebdbda3dd5d0
permissions -rw-r--r--
add utils.to/from_utc_timestamp functions, fix LogSearchIndex to store all LogLine attributes, add list() method to get LogLines for a given date, and improve scripts/search-index
"""
    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 from_utc_timestamp(int(timestamp_str))
    
    def build (self, dtz) :
        """
            pytz.utc datetime.datetime -> timestamp_str
        """
        
        return str(to_utc_timestamp(dtz))

def from_utc_timestamp (timestamp) :
    """
        Converts a UNIX timestamp into a datetime.datetime
    """

    return datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc)

def to_utc_timestamp (dt) :
    """
        Converts a datetime.datetime into a UNIX timestamp
    """

    return calendar.timegm(dt.utctimetuple())