utils.py
author Tero Marttila <terom@fixme.fi>
Wed, 11 Feb 2009 03:46:59 +0200
changeset 99 8719ac564b22
parent 95 ebdbda3dd5d0
child 115 751e3fcd11d2
permissions -rw-r--r--
implement non-blocking locking for the estdb, and our own locking for the autoload statetmpfile... it should work well now
"""
    Miscellaneous things
"""

import datetime, calendar, pytz
import os, errno

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())

def mtime (path, ignore_missing=False) :
    """
        Gets the mtime for the given path as an UTC datetime, or None, if the file doesn't exist and ignore_missing
    """

    try :
        # stat
        st = os.stat(path)
    
    # trap IOError
    except os.error, e :
        # ENOENT?
        if ignore_missing and e.errno == errno.ENOENT :
            return None

        else :
            raise

    else :
        # decode
        return from_utc_timestamp(st.st_mtime)