Ophelia utilities

Namespaces

Handling a request involves namespaces for a number of things, e.g. for the page template context, or the request environment variables. This need is in principle served by plain Python dictionaries. However, it sometimes feels more convenient and natural to access a particular namespace member as an object attribute rather than by a key reference. Namespaces are Python dictionaries which expose their values as attributes:

>>> from ophelia.util import Namespace
>>> Namespace()
{}
>>> ns = Namespace(foo="bar")
>>> ns
{'foo': 'bar'}
>>> ns["foo"]
'bar'
>>> ns.foo
'bar'
>>> ns.foo = "baz"
>>> ns["foo"]
'baz'
>>> ns["asdf"] = "fdsa"
>>> ns.asdf
'fdsa'

Dictionary methods work as expected, e.g. update():

>>> a = Namespace()
>>> a.foo = 1
>>> b = Namespace()
>>> b.bar = 2
>>> a.update(b)
>>> a.bar
2

Unicode dates and times

Ophelia provides its own version of strftime which always returns unicode. It works the same as the time.strftime function otherwise. With only a format string given, it formats the current time:

>>> from ophelia.util import strftime
>>> strftime("%c")
u'...'

Our strftime function uses the current locale’s encoding to decode time.strftime’s output, as that is what time.strftime uses to encode it in the first place. We’d like to try it out but we cannot be sure of the availability of any particular interesting locale. Therefore we use a boring one to demonstrate the call at all:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "C")
'C'
>>> import datetime
>>> strftime("%B", datetime.date(2007, 3, 1))
u'March'

Not only do we always get unicode output from our strftime function, but we can also pass it a unicode format string (which time.strftime would not accept):

>>> strftime(u"The third month is named %B...", datetime.date(2007, 3, 1))
u'The third month is named March...'

However, to avoid confusion with the locale’s encoding which we don’t even want to think about when calling strftime, we cannot pass any encoded strings as the format specification:

>>> strftime("Im sch\xf6nen Monat %B...", datetime.date(2007, 3, 1))
Traceback (most recent call last):
UnicodeDecodeError: 'ascii' codec can't decode byte ... in position ...