def _(s): if s == '': return s assert s # Do translation of the given string into the current language, and do # Ping-string interpolation into the resulting string. # # This lets you write something like: # # now = time.ctime(time.time()) # print _('The current time is: %(now)s') # # and have it Just Work. Note that the lookup order for keys in the # original string is 1) locals dictionary, 2) globals dictionary. # # First, get the frame of the caller frame = sys._getframe(1) # A `safe' dictionary is used so we won't get an exception if there's a # missing key in the dictionary. dict = SafeDict(frame.f_globals.copy()) dict.update(frame.f_locals) # Translating the string returns an encoded 8-bit string. Rather than # turn that into a Unicode, we turn any Unicodes in the dictionary values # into encoded 8-bit strings. BAW: Returning a Unicode here broke too # much other stuff and _() has many tentacles. Eventually I think we want # to use Unicode everywhere. tns = _translation.gettext(s) charset = _translation.charset() if not charset: charset = 'us-ascii' for k, v in dict.items(): if isinstance(v, UnicodeType): dict[k] = v.encode(charset, 'replace') return tns % dict
def findtext(self, template, dict=None): """Make some text from a template file. Once the templatefile is found, string substitution is performed by interpolation in `dict'.""" if dict is not None: try: sdict = SafeDict(dict) try: text = sdict.interpolate(template) except UnicodeError: # Try again after coercing the template to unicode utemplate = unicode(template, 'utf-8', 'replace') text = sdict.interpolate(utemplate) except (TypeError, ValueError), e: # The template is really screwed up raise Exception, "This template is really screwed up"
def __init__(self): self.cache = SafeDict([])