Source

muyhomepage2 / muyhomepage2 / util.py

Full commit
John Mulligan 8aabed9 










John Mulligan dc06256 
John Mulligan 79050d8 
John Mulligan 8aabed9 
John Mulligan dc06256 




John Mulligan 8aabed9 



John Mulligan 347da89 
John Mulligan 8aabed9 
John Mulligan 79050d8 
John Mulligan 8aabed9 



John Mulligan 79050d8 
John Mulligan 8aabed9 








John Mulligan 3f49883 













John Mulligan dc06256 











John Mulligan 3f50973 


John Mulligan dc06256 




















#!/usr/bin/env python
#
# Copyright 2009 John Mulligan <phlogistonjohn@asynchrono.us>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
#
"""utility functions
"""

import string
import time, calendar
from hashlib import md5

TIME_FMT_MUY    = '%Y-%m-%d %H:%M %Z'
TIME_FMT_822    = '%a, %d %b %Y %H:%M:%S %Z'
TIME_FMT_3339   = '%Y-%m-%dT%H:%M:%SZ'
TIME_FMT_ATOMID = '%Y-%m-%d'


def encodetitle(title):
    """Create a simplified title string.
    """
    assert title, "empty title string"
    permitted = string.letters + string.digits + ':'
    eliminate = "'"
    temp = []
    for ch in title.lower():
        if ch in permitted:
            temp.append(ch)
        elif temp[-1] == '-' or ch in eliminate:
            pass
        else:
            temp.append('-')
    # elminate leading and trailing dashes
    while temp[0] == '-':
        temp = temp[1:]
    while temp[-1] == '-':
        temp = temp[:-1]
    return ''.join(temp)


def contentcode(filename):
    csum = md5()
    fp = open(filename)
    try:
        while True:
            buf = fp.read(8192)
            if not buf:
                break
            csum.update(buf)
    finally:
        fp.close()
    return csum.hexdigest()


class When(object):
    def __init__(self, wtime):
        self._time = wtime

    def local(self):
        return time.localtime(self._time)

    def utc(self):
        return time.gmtime(self._time)

    def __int__(self):
        return int(self._time)

    def __str__(self):
        return time.strftime(TIME_FMT_MUY, self.local())

    def storefmt(self):
        return time.strftime(TIME_FMT_MUY, self.utc())

    @classmethod
    def parse(cls, txt):
        utc = True
        if not txt.endswith("UTC"):
            utc = False
        tm = time.strptime(txt, TIME_FMT_MUY)
        if utc:
            etime = calendar.timegm(tm) 
        else:
            etime = time.mktime(tm)
        return cls(etime)

    @classmethod
    def now(cls):
        return cls(time.time())