class I18nAwareContentObject(object): implements(II18nAware) def __init__(self): self.content = {} self.defaultLanguage = 'en' def getContent(self, language): return self.content[language] def queryContent(self, language, default=None): return self.content.get(language, default) def setContent(self, content, language): self.content[language] = content ############################################################ # Implementation methods for interface # II18nAware.py def getDefaultLanguage(self): 'See II18nAware' return self.defaultLanguage def setDefaultLanguage(self, language): 'See II18nAware' self.defaultLanguage = language def getAvailableLanguages(self): 'See II18nAware' return self.content.keys()
class LocaleTimeZone(object): """Specifies one of the timezones of a specific locale. The attributes of this class are not inherited, since all timezone information is always provided together. Example:: >>> tz = LocaleTimeZone('Europe/Berlin') >>> tz.cities = ['Berlin'] >>> tz.names = {'standard': ('Mitteleuropaeische Zeit', 'MEZ'), ... 'daylight': ('Mitteleuropaeische Sommerzeit', 'MESZ')} >>> tz.type 'Europe/Berlin' >>> tz.cities ['Berlin'] """ implements(ILocaleTimeZone) def __init__(self, type): """Initialize the object.""" self.type = type self.cities = [] self.names = {}
class ContextDependent(object): """standard boilerplate for context dependent objects""" implements(IContextDependent) def __init__(self, context): self.context = context
class Factory(object): """Generic factory implementation. The purpose of this implementation is to provide a quick way of creating factories for classes, functions and other objects. """ implements(IFactory) def __init__(self, callable, title='', description='', interfaces=None): self._callable = callable self.title = title self.description = description self._interfaces = interfaces def __call__(self, *args, **kw): return self._callable(*args, **kw) def getInterfaces(self): if self._interfaces is not None: spec = Implements(*self._interfaces) spec.__name__ = getattr(self._callable, '__name__', '[callable]') return spec return implementedBy(self._callable) def __repr__(self): return '<%s for %s>' %(self.__class__.__name__, `self._callable`)
class State(object): __slots__ = 'value', 'title' implements(interfaces.ITerm) def __init__(self, value, title): self.value = value self.title = title
class Text(MinMaxLen, Field): """A field containing text used for human discourse.""" _type = unicode implements(IFromUnicode) def __init__(self, *args, **kw): super(Text, self).__init__(*args, **kw) def fromUnicode(self, str): """ >>> t = Text(constraint=lambda v: 'x' in v) >>> t.fromUnicode("foo x spam") Traceback (most recent call last): ... WrongType: ('foo x spam', <type 'unicode'>) >>> t.fromUnicode(u"foo x spam") u'foo x spam' >>> t.fromUnicode(u"foo spam") Traceback (most recent call last): ... ConstraintNotSatisfied: foo spam """ self.validate(str) return str
class GettextMessageCatalog(object): """A message catalog based on GNU gettext and Python's gettext module.""" implements(IGlobalMessageCatalog) def __init__(self, language, domain, path_to_file): """Initialize the message catalog""" self.language = language self.domain = domain self._path_to_file = path_to_file self.reload() self._catalog.add_fallback(_KeyErrorRaisingFallback()) def reload(self): 'See IMessageCatalog' fp = open(self._path_to_file, 'rb') try: self._catalog = GNUTranslations(fp) finally: fp.close() def getMessage(self, id): 'See IMessageCatalog' return self._catalog.ugettext(id) def queryMessage(self, id, default=None): 'See IMessageCatalog' try: return self._catalog.ugettext(id) except KeyError: return default def getIdentifier(self): 'See IMessageCatalog' return self._path_to_file
class TestClass(object): implements(ITestSchema) _foo = u'' _bar = u'' _attribute = u'' def getfoo(self): return self._foo def setfoo(self, value): self._foo = value foo = property(getfoo, setfoo, None, u'foo') def getbar(self): return self._bar def setbar(self, value): self._bar = value bar = property(getbar, setbar, None, u'foo') def getattribute(self): return self._attribute def setattribute(self, value): self._attribute = value attribute = property(getattribute, setattribute, None, u'attribute')
class FieldPropertyTestClass(object): implements(ITestSchema) foo = FieldProperty(ITestSchema['foo']) bar = FieldProperty(ITestSchema['bar']) attribute = FieldProperty(ITestSchema['attribute'])
class Env(object): implements(IUserPreferredLanguages) def __init__(self, langs=()): self.langs = langs def getPreferredLanguages(self): return self.langs
class Comp(object): __used_for__ = IContent implements(IApp) def __init__(self, *args): # Ignore arguments passed to constructor pass a = 1 def f(): pass
class LocaleFormatLength(AttributeInheritance): """Specifies one of the format lengths of a specific quantity, like numbers, dates, times and datetimes.""" implements(ILocaleFormatLength) def __init__(self, type=None): """Initialize the object.""" self.type = type self.default = None
class Ob(object): implements(I1) def __conform__(self, i): if i is IServiceService: from zpt._zope.component.bbb import getServices return getServices() from zpt._zope.component.interfaces import ISiteManager from zpt._zope.component import getSiteManager if i is ISiteManager: return getSiteManager()
class Good(object): implements(I) def __init__(self): self.set = 0 def getFoo(self): return u"foo" def setFoo(self, v): self.set += 1
class LocaleCurrency(object): """Simple implementation of ILocaleCurrency without inheritance support, since it is not needed for a single currency.""" implements(ILocaleCurrency) def __init__(self, type): """Initialize object.""" self.type = type self.symbol = None self.symbolChoice = False self.displayName = None
class ErrorInfo(object): implements(ITALExpressionErrorInfo) def __init__(self, err, position=(None, None)): if isinstance(err, Exception): self.type = err.__class__ self.value = err else: self.type = err self.value = None self.lineno = position[0] self.offset = position[1]
class DeferExpr(object): implements(ITALESExpression) def __init__(self, name, expr, compiler): self._s = expr = expr.lstrip() self._c = compiler.compile(expr) def __call__(self, econtext): return DeferWrapper(self._c, econtext) def __repr__(self): return '<DeferExpr %s>' % ` self._s `
class NotExpr(object): implements(ITALESExpression) def __init__(self, name, expr, engine): self._s = expr = expr.lstrip() self._c = engine.compile(expr) def __call__(self, econtext): return int(not econtext.evaluateBoolean(self._c)) def __repr__(self): return '<NotExpr %s>' % ` self._s `
class LocaleProvider(object): """A locale provider that get's its data from the XML data.""" implements(ILocaleProvider) def __init__(self, locale_dir): self._locales = {} self._locale_dir = locale_dir def loadLocale(self, language=None, country=None, variant=None): """See zpt._zope.i18n.interfaces.locales.ILocaleProvider""" # Creating the filename if language == None and country == None and variant == None: filename = 'root.xml' else: filename = language if country is not None: filename += '_'+country if variant is not None: if '_' not in filename: filename += '_' filename += '_'+variant filename += '.xml' # Making sure we have this locale path = os.path.join(self._locale_dir, filename) if not os.path.exists(path): raise LoadLocaleError, \ 'The desired locale is not available.\nPath: %s' %path # Import here to avoid circular imports from zpt._zope.i18n.locales.xmlfactory import LocaleFactory # Let's get it! locale = LocaleFactory(path)() self._locales[(language, country, variant)] = locale def getLocale(self, language=None, country=None, variant=None): """See zpt._zope.i18n.interfaces.locales.ILocaleProvider""" # We want to be liberal in what we accept, but the standard is lower # case language codes, upper case country codes, and upper case # variants, so coerce case here. if language: language = language.lower() if country: country = country.upper() if variant: variant = variant.upper() if not self._locales.has_key((language, country, variant)): self.loadLocale(language, country, variant) return self._locales[(language, country, variant)]
class ErrorInfo(object): """Information about an exception passed to an on-error handler.""" if tal: implements(ITALExpressionErrorInfo) def __init__(self, err, position=(None, None)): if isinstance(err, Exception): self.type = err.__class__ self.value = err else: self.type = err self.value = None self.lineno = position[0] self.offset = position[1]
class LocaleFormat(object): """Specifies one of the format of a specific format length. The attributes of this class are not inherited, since all format information is always provided together. Note that this information by itself is often not useful, since other calendar data is required to use the specified pattern for formatting and parsing. """ implements(ILocaleFormat) def __init__(self, type=None): """Initialize the object.""" self.type = type self.displayName = u'' self.pattern = u''
class StubServiceService(object): implements(IServiceService) # This is a lie. def __init__(self): self.services = {} from zpt._zope.component.site import GlobalSiteManager self.sm = GlobalSiteManager() def setService(self, name, service): self.services[name] = service def getService(self, name): try: return self.services[name] except KeyError: raise ComponentLookupError, name
class LocaleIdentity(object): """Represents a unique identification of the locale This class does not have to deal with inheritance. Examples:: >>> id = LocaleIdentity('en') >>> id <LocaleIdentity (en, None, None, None)> >>> id = LocaleIdentity('en', 'latin') >>> id <LocaleIdentity (en, latin, None, None)> >>> id = LocaleIdentity('en', 'latin', 'US') >>> id <LocaleIdentity (en, latin, US, None)> >>> id = LocaleIdentity('en', 'latin', 'US', 'POSIX') >>> id <LocaleIdentity (en, latin, US, POSIX)> >>> id = LocaleIdentity('en', None, 'US', 'POSIX') >>> id <LocaleIdentity (en, None, US, POSIX)> """ implements(ILocaleIdentity) def __init__(self, language=None, script=None, territory=None, variant=None): """Initialize object.""" self.language = language self.script = script self.territory = territory self.variant = variant def __repr__(self): """See zpt._zope.i18n.interfaces.ILocaleIdentity """ return "<LocaleIdentity (%s, %s, %s, %s)>" % ( self.language, self.script, self.territory, self.variant)
class StateVocabulary(object): __slots__ = () implements(IStateVocabulary) def __init__(self, object=None): pass def __contains__(self, value): return value in _states def __iter__(self): return _states.itervalues() def __len__(self): return len(_states) def getTerm(self, value): return _states[value]
class TestNameSpace(object): implements(ITALESFunctionNamespace) def __init__(self, context): self.context = context def setEngine(self, engine): self._engine = engine def engine(self): return self._engine def upper(self): return str(self.context).upper() def __getitem__(self, key): if key == 'jump': return self.context._d raise KeyError, key
class SampleVocabulary(object): implements(interfaces.IVocabulary) def __iter__(self): return iter([self.getTerm(x) for x in range(0, 10)]) def __contains__(self, value): return 0 <= value < 10 def __len__(self): return 10 def getTerm(self, value): if value in self: t = SampleTerm() t.value = value t.double = 2 * value return t raise LookupError("no such value: %r" % value)
class SimpleTranslationDomain(object): """This is the simplest implementation of the ITranslationDomain I could come up with. The constructor takes one optional argument 'messages', which will be used to do the translation. The 'messages' attribute has to have the following structure: {('language', 'msg_id'): 'message', ...} Note: This Translation Domain does not use message catalogs. """ implements(ITranslationDomain) # See zpt._zope.i18n.interfaces.ITranslationDomain domain = None def __init__(self, domain, messages=None): """Initializes the object. No arguments are needed.""" self.domain = domain if messages is None: self.messages = {} else: assert isinstance(messages, dict) self.messages = messages def translate(self, msgid, mapping=None, context=None, target_language=None, default=None): '''See interface ITranslationDomain''' # Find out what the target language should be if target_language is None and context is not None: langs = [m[0] for m in self.messages.keys()] # Let's negotiate the language to translate to. :) negotiator = getUtility(INegotiator) target_language = negotiator.getLanguage(langs, context) # Find a translation; if nothing is found, use the default # value text = self.messages.get((target_language, msgid)) if text is None: text = default return interpolate(text, mapping)
class StringExpr(object): implements(ITALESExpression) def __init__(self, name, expr, engine): self._s = expr if '%' in expr: expr = expr.replace('%', '%%') self._vars = vars = [] if '$' in expr: # Use whatever expr type is registered as "path". path_type = engine.getTypes()['path'] parts = [] for exp in expr.split('$$'): if parts: parts.append('$') m = _interp.search(exp) while m is not None: parts.append(exp[:m.start()]) parts.append('%s') vars.append( path_type('path', m.group(1) or m.group(2), engine)) exp = exp[m.end():] m = _interp.search(exp) if '$' in exp: raise engine.getCompilerError()( '$ must be doubled or followed by a simple path') parts.append(exp) expr = ''.join(parts) self._expr = expr def __call__(self, econtext): vvals = [] for var in self._vars: v = var(econtext) vvals.append(v) return self._expr % tuple(vvals) def __str__(self): return 'string expression (%s)' % ` self._s ` def __repr__(self): return '<StringExpr %s>' % ` self._s `
class AdapterService(object): """Base implementation of an adapter service, implementing only the 'IAdapterService' interface. No write-methods were implemented. """ implements(IAdapterService) def __init__(self, sitemanager=None): if sitemanager is None: from zpt._zope.component.site import GlobalSiteManager sitemanager = GlobalSiteManager() self.sm = sitemanager def __getattr__(self, name): attr = getattr(self.sm.adapters, name) if attr is not None: return attr raise AttributeError, name
class POEngine(DummyEngine): implements(ITALExpressionEngine) def __init__(self, macros=None): self.catalog = {} DummyEngine.__init__(self, macros) def evaluate(*args): # If the result of evaluate ever gets into a message ID, we want # to notice the fact in the .pot file. return '${DYNAMIC_CONTENT}' def evaluatePathOrVar(*args): # Actually this method is never called. return 'XXX' def evaluateSequence(self, expr): return (0,) # dummy def evaluateBoolean(self, expr): return True # dummy def translate(self, msgid, domain=None, mapping=None, default=None, # Position is not part of the ITALExpressionEngine # interface position=None): # Make the message is a MessageID object, if the default differs # from the value, so that the POT generator can put the default # text into a comment. if default is not None and normalize(default) != msgid: msgid = MessageID(msgid, default=default) if domain not in self.catalog: self.catalog[domain] = {} domain = self.catalog[domain] if msgid not in domain: domain[msgid] = [] domain[msgid].append((self.file, position)) return 'x'