def registerAdapter(adapterFactory, origInterface, *interfaceClasses): from nevow.util import _namedAnyWithBuiltinTranslation, _NamedAnyError isStr = type(adapterFactory) is str if (type(origInterface) is str) != isStr: raise ValueError( "Either all arguments must be strings or all must be objects.") for interfaceClass in interfaceClasses: if (type(interfaceClass) is str) != isStr: raise ValueError( "Either all arguments must be strings or all must be objects.") if isStr: # print "registerAdapter:",adapterFactory, origInterface, interfaceClasses adapterFactory = _namedAnyWithBuiltinTranslation(adapterFactory) origInterface = _namedAnyWithBuiltinTranslation(origInterface) interfaceClasses = [ _namedAnyWithBuiltinTranslation(x) for x in interfaceClasses ] if 'nevow.inevow.ISerializable' in interfaceClasses or [ o for o in interfaceClasses if getattr(o, '__name__', None) == 'ISerializable' ]: warnings.warn( "ISerializable is deprecated. Please use nevow.flat.registerFlattener instead.", stacklevel=2) from nevow import flat flat.registerFlattener(adapterFactory, origInterface) _registerAdapter(adapterFactory, origInterface, *interfaceClasses)
def registerAdapter(adapterFactory, origInterface, *interfaceClasses): for inter in interfaceClasses: if getattr(inter, '__name__', inter).endswith('ISerializable'): warnings.warn("ISerializable is deprecated; please use nevow.flat.registerFlattener instead: %s %s" % (adapterFactory, origInterface), stacklevel=2) from nevow.flat import registerFlattener registerFlattener(adapterFactory, origInterface) return theAdapterRegistry.registerAdapter(adapterFactory, origInterface, *interfaceClasses)
def __init__(self, factory): ''' Constructor @param factory: ScrabbleServerFactory ''' rend.Page.__init__(self) self.factory = factory flat.registerFlattener(self.flattenTime, util.Time) r = manager.ResourceManager() ScrabbleSite.child_styles = static.File( r["resources"]["web"].path ) ScrabbleSite.docFactory = loaders.xmlfile( r["resources"]["web"]["index.html"] )
def registerAdapter(adapterFactory, origInterface, *interfaceClasses): for inter in interfaceClasses: if getattr(inter, '__name__', inter).endswith('ISerializable'): warnings.warn( "ISerializable is deprecated; please use nevow.flat.registerFlattener instead: %s %s" % (adapterFactory, origInterface), stacklevel=2) from nevow.flat import registerFlattener registerFlattener(adapterFactory, origInterface) return theAdapterRegistry.registerAdapter(adapterFactory, origInterface, *interfaceClasses)
def __init__(self, factory): ''' Constructor @param factory: ScrabbleServerFactory ''' rend.Page.__init__(self) self.factory = factory flat.registerFlattener(self.flattenTime, util.Time) r = manager.ResourceManager() ScrabbleSite.child_styles = static.File(r["resources"]["web"].path) ScrabbleSite.docFactory = loaders.xmlfile( r["resources"]["web"]["index.html"])
return tag def makeWidgetFactory(code): return eval(code) ############# formal adapters for DaCHS objects # column options from gavo.rscdef import column class ToFormalAdapter(object): implements(iformal.ILabel, iformal.IKey) def __init__(self, original): self.original = original def label(self): return unicode(self.original.title) def key(self): return unicode(self.original.content_) components.registerAdapter(ToFormalAdapter, column.Option, iformal.ILabel) components.registerAdapter(ToFormalAdapter, column.Option, iformal.IKey) flat.registerFlattener(lambda original, ctx: str(original), utils.QuotedName)
def remember(ctx, data): ctx.remember([('replace', ['currentView', headers[i][1]], {})], inevow.IViewParameters) return ctx.tag if currentView != headers[i][1]: continue yield T.div(id="switch_%s" % i, style=style, render=remember)[ body ] yield T.div(style="margin-top: 4px")[ genbodies() ] def noDefault(ctx, data): return "" flat.registerFlattener(noDefault, Options._NoDefaultOption) class PreferencesPage(rend.Page): def render_message(self, ctx, _): msg = ctx.arg('message') if msg is not None: return T.div(id="message")[msg] return '' def render_switcher(self, ctx, allOptions): def genSwitchers(): for opt in allOptions: name = opt.getName() print name if name in interesting:
compy.registerAdapter(FeedContainer, IFeed, inevow.IContainer) class IText(Interface): #### required dom = Attribute("DOM tree of document ready to be inlined.") invariant(required('dom')) def flattenIText(orig, ctx): assert orig.dom.nodeType == orig.dom.ELEMENT_NODE assert orig.dom.namespaceURI == 'http://www.w3.org/1999/xhtml' assert orig.dom.nodeName == 'div' for node in orig.dom.childNodes: yield tags.xml(node.toxml()) flat.registerFlattener(flattenIText, IText) class IContent(Interface): """ An Atom v1.0 feed entry content. Consider this Interface an abstract superclass only. You should always implement IInlineContent or ILinkedContent. """ type = Attribute("One of 'text', 'html' or 'xhtml', or media type of content.") invariant(required('type')) # TODO type is really more freeform, I'm just not supporting those yet class IInlineContent(IContent, IText): """Feed entry content that is inlined in the feed."""
if name == 'dn': return self.original.dn elif name == 'attributes': return _DictLike(self.original) else: return None components.registerAdapter( LDAPEntryContainer, ldapsyntax.LDAPEntryWithClient, inevow.IContainer) def dnSerializer(original, context): return flat.serialize(str(original), context) flat.registerFlattener(dnSerializer, distinguishedname.DistinguishedName) def entrySerializer(original, context): ul = tags.ul() for a,l in original.items(): if len(l)==0: ul[tags.li[a, ': none']] elif len(l)==1: for attr in l: first = attr break ul[tags.li[a, ': ', first]] else: li=tags.li[a, ':'] ul[li] liul=tags.ul()
if not _PublicCmsReSTWriter: _PublicCmsReSTWriter = Writer() _PublicCmsReSTWriter.translator_class = _PublicReSTTranslator return _PublicCmsReSTWriter def RichTextFlattener(original, ctx): xml = original.htmlFragment(restWriter=getPublicCmsReSTWriter()) return _xml2ReSTFragment(xml) from cms.widgets import richtext if flat.getFlattener(richtext.RichTextData(None)): raise '*** Rich Text Flattener already registered' flat.registerFlattener(RichTextFlattener, richtext.RichTextData) def str2ReSTFragment(str): xml = htmlFragment(str, writer=getPublicCmsReSTWriter()) return _xml2ReSTFragment(xml) def _xml2ReSTFragment(xml): XML_TEMPLATE = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <div xmlns:n="http://nevow.com/ns/nevow/0.1" >%(xml)s</div>""" xml = XML_TEMPLATE%{'xml':xml}
def loadFlatteners(S): for line in S.split('\n'): line = line.strip() if line and not line.startswith('#'): f, o = line.split() flat.registerFlattener(f, clean(o))
DATETIME_FORMAT = DATE_FORMAT + ', ' + TIME_FORMAT def dateFlattener(date, ctx): return date.strftime(DATE_FORMAT) def timeFlattener(time, ctx): return time.strftime(TIME_FORMAT) def datetimeFlattener(datetime, ctx): return datetime.strftime(DATETIME_FORMAT) flat.registerFlattener(dateFlattener, datetime.date) flat.registerFlattener(timeFlattener, datetime.time) flat.registerFlattener(datetimeFlattener, datetime.datetime) def RichTextFlattener(original, ctx): from cms.widgets.restsupport import publicCmsReSTWriter return T.xml(original.htmlFragment(restWriter=publicCmsReSTWriter)) from cms.widgets import richtext if flat.getFlattener( richtext.RichTextData(None) ) is None: flat.registerFlattener(RichTextFlattener, richtext.RichTextData)
def gotData(data, ctx): if hasattr(data, 'sort'): data.sort(key=lambda i: i.date, reverse=True) resource = inevow.IResource(data) #if itemsel.template is not None and hasattr(resource, 'setTemplate'): #resource.setTemplate(*parseTemplateString(itemsel.template)) return resource itemsel = ItemSelection.fromString(str(original)) d = inevow.IGettable(itemsel).get(ctx) d.addCallback(gotData, ctx) return d def CmsFragmentFlattener(original,ctx): def gotData(data, ctx): if hasattr(data, 'sort'): data.sort(key=lambda i: i.date, reverse=True) resource = inevow.IResource(data) #if itemsel.template is not None and hasattr(resource, 'setTemplate'): #resource.setTemplate(*parseTemplateString(itemsel.template)) return resource itemsel = ItemSelection.fromString(str(original)) d = inevow.IGettable(itemsel).get(ctx) d.addCallback(gotData, ctx) return d flat.registerFlattener(RestFlattener, Y.rest) flat.registerFlattener(HtmlFlattener, Y.html) flat.registerFlattener(CmsItemSelFlattener, Y.cmsitemsel)
of this attribute lookup passed to your handler.""" return ["_a", self.id, attr] def requestMethod(self, method, *args): """You can pass me as an extra argument to addHandler to get the result of this method passed to your handler.""" return ["_m", self.id, method, list(args)] def addHandler(self, event, handler, *args): args = [u"'%s'" % event] + [repr(a) for a in args] call = u'rCall(this, %s)' % ', '.join(args) self.handlers[event] = (handler, call) self.kwargs[event] = call return self flat.registerFlattener(lambda orig, ctx: orig.rend(ctx), GenericWidget) # -------------------------------------------------------------------- class Window(GenericWidget): def __init__(self, *xmlNameSpaces, **kwargs): if kwargs.has_key('id'): GenericWidget.__init__(self, kwargs['id']) else: GenericWidget.__init__(self) kwargs.update({'id' : self.id}) kwargs.setdefault('onload', u'server.callRemote("live");') self.kwargs = kwargs
DATE_FORMAT = '%d/%m/%Y' TIME_FORMAT = '%H:%M' DATETIME_FORMAT = DATE_FORMAT + ', ' + TIME_FORMAT def dateFlattener(date, ctx): return date.strftime(DATE_FORMAT) def timeFlattener(time, ctx): return time.strftime(TIME_FORMAT) def datetimeFlattener(datetime, ctx): return datetime.strftime(DATETIME_FORMAT) flat.registerFlattener(dateFlattener, datetime.date) flat.registerFlattener(timeFlattener, datetime.time) flat.registerFlattener(datetimeFlattener, datetime.datetime) def debug(r, mess): print '>>DEBUG', mess, r return r
class SingleQuote(object): def __init__(self, children): self.children = children def __repr__(self): return "%s(%s)" % (type(self).__name__, self.children) def flattenSingleQuote(singleQuote, ctx): new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString=True) return flat.serialize(singleQuote.children, new) flat.registerFlattener(flattenSingleQuote, SingleQuote) class _js(object): """ Stan for Javascript. There is a convenience instance of this class named "js" in the livepage module which you should use instead of the _js class directly. Marker indicating literal Javascript should be rendered. No escaping will be performed. When inside a JavascriptContext, Nevow will automatically put apostrophe quote marks around any Python strings it renders. This makes turning a Python string into a JavaScript string very easy. However, there are often situations where you wish to
# print "registerAdapter:",adapterFactory, origInterface, interfaceClasses adapterFactory = namedAny(adapterFactory) origInterface = namedAny(origInterface) interfaceClasses = [namedAny(x) for x in interfaceClasses] except _NamedAnyError, nae: print 'NamedAnyError:', nae return # print "_registerAdapter:",adapterFactory, origInterface, interfaceClasses if 'nevow.inevow.ISerializable' in interfaceClasses or filter( lambda o: getattr(o, '__name__', None) == 'ISerializable', interfaceClasses): warnings.warn( "ISerializable is deprecated. Please use nevow.flat.registerFlattener instead.", stacklevel=2) from nevow import flat flat.registerFlattener(adapterFactory, origInterface) _registerAdapter(adapterFactory, origInterface, *interfaceClasses) class IComponentized(Interface): pass _Componentized = Componentized class Componentized(_Componentized): __implements__ = (IComponentized, ) def __init__(self, adapterCache=None): _Componentized.__init__(self)
class TagNamespace(TagGenerator): tagFactory = NSProto def __init__(self, namespace, uri, *args, **kwargs): self.namespace = namespace self.uri = uri TagGenerator.__init__(self, *args, **kwargs) def makeTagName(self, name): return "%s:%s" % (self.namespace, name) flat.registerFlattener(lambda orig, ctx: orig.uri, TagNamespace) class PrimaryNamespace(TagNamespace): tagFactory = NSProto def makeTagName(self, name): return name if __name__ == '__main__': from nevow.flat.ten import flatten h = PrimaryNamespace( 'html', "http://www.w3.org/2002/06/xhtml2",
return self.original.dn elif name == 'attributes': return _DictLike(self.original) else: return None compy.registerAdapter(LDAPEntryContainer, ldapsyntax.LDAPEntryWithClient, inevow.IContainer) def dnSerializer(original, context): return flat.serialize(str(original), context) flat.registerFlattener(dnSerializer, distinguishedname.DistinguishedName) def entrySerializer(original, context): ul = tags.ul() for a, l in original.items(): if len(l) == 0: ul[tags.li[a, ': none']] elif len(l) == 1: for attr in l: first = attr break ul[tags.li[a, ': ', first]] else: li = tags.li[a, ':'] ul[li]
if isStr: try: # print "registerAdapter:",adapterFactory, origInterface, interfaceClasses adapterFactory = namedAny(adapterFactory) origInterface = namedAny(origInterface) interfaceClasses = [namedAny(x) for x in interfaceClasses] except _NamedAnyError, nae: print 'NamedAnyError:', nae return # print "_registerAdapter:",adapterFactory, origInterface, interfaceClasses if 'nevow.inevow.ISerializable' in interfaceClasses or filter( lambda o: getattr(o, '__name__', None) == 'ISerializable', interfaceClasses): warnings.warn("ISerializable is deprecated. Please use nevow.flat.registerFlattener instead.", stacklevel=2) from nevow import flat flat.registerFlattener(adapterFactory, origInterface) _registerAdapter(adapterFactory, origInterface, *interfaceClasses) class IComponentized(Interface): pass _Componentized = Componentized class Componentized(_Componentized): __implements__ = (IComponentized,) def __init__(self, adapterCache=None): _Componentized.__init__(self) if adapterCache: for k, v in adapterCache.items(): self.setComponent(k, v)
# TODO need to make this pretty some day. for c in [ pureldap.LDAPFilter_and, pureldap.LDAPFilter_or, pureldap.LDAPFilter_not, pureldap.LDAPFilter_substrings, pureldap.LDAPFilter_equalityMatch, pureldap.LDAPFilter_greaterOrEqual, pureldap.LDAPFilter_lessOrEqual, pureldap.LDAPFilter_approxMatch, pureldap.LDAPFilter_present, pureldap.LDAPFilter_extensibleMatch, ]: flat.registerFlattener(LDAPFilterSerializer, c) class AddressBookResource(rend.Page): docFactory = loaders.xmlfile('searchform.xhtml', templateDir=os.path.split( os.path.abspath(__file__))[0]) def configurable_(self, context): try: i = context.locate(inevow.IHand) except KeyError: i = CurrentSearch() return i def data_search(self, context, data):
from nevow import flat, tags from mako.runtime import supports_caller, Undefined from nevow import flat, tags ## Undefined mako args should return empty strings flat.registerFlattener(lambda o, ctx: "", Undefined) @supports_caller def form(context, action="", method="post"): context.write('<form action="%s" method="%s">' % (action, method)) context['caller'].body() context.write("</form>") return '' def maketag(context, tag, default, kwargs, content=None): default.update(kwargs) if content is not None: t = tag(**default)[content] else: t = tag(**default) context.write(flat.flatten(t)) return "" def submit(context, **kwargs): default = {'value': "Submit", 'type': "submit", 'id': "submit"} return maketag(context, tags.input, default, kwargs)
class ClientSideException(Exception): pass class SingleQuote(object): def __init__(self, children): self.children = children def __repr__(self): return "%s(%s)" % (type(self).__name__, self.children) def flattenSingleQuote(singleQuote, ctx): new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString=True) return flat.serialize(singleQuote.children, new) flat.registerFlattener(flattenSingleQuote, SingleQuote) class _js(object): """Stan for Javascript. There is a convenience instance of this class named "js" in the livepage module which you should use instead of the _js class directly. Marker indicating literal Javascript should be rendered. No escaping will be performed. When inside a JavascriptContext, Nevow will automatically put apostrophe quote marks around any Python strings it renders. This makes turning a Python string into a JavaScript string very easy. However, there are often situations where you wish to generate some literal Javascript code and do not wish quote
return original.asText() # TODO need to make this pretty some day. for c in [ pureldap.LDAPFilter_and, pureldap.LDAPFilter_or, pureldap.LDAPFilter_not, pureldap.LDAPFilter_substrings, pureldap.LDAPFilter_equalityMatch, pureldap.LDAPFilter_greaterOrEqual, pureldap.LDAPFilter_lessOrEqual, pureldap.LDAPFilter_approxMatch, pureldap.LDAPFilter_present, pureldap.LDAPFilter_extensibleMatch, ]: flat.registerFlattener(LDAPFilterSerializer, c) class AddressBookResource(rend.Page): docFactory = loaders.xmlfile( 'searchform.xhtml', templateDir=os.path.split(os.path.abspath(__file__))[0]) def configurable_(self, context): try: i = context.locate(inevow.IHand) except KeyError: i = CurrentSearch() return i def data_search(self, context, data): d = defer.maybeDeferred(self.locateConfigurable, context, '')
if not self._name: name, = args return self.__class__(name) return self.__class__(callJS(self._name, *args)) def __getitem__(self, args): if not isinstance(args, tuple): args = (args,) return self.__class__(self._name+'['+','.join(map(str, _quoteJSArguments(args)))+']') def __str__(self): return self._name js = _js() flat.registerFlattener(lambda original, ctx: str(original), _js) document = _js('document') window = _js('window') this = _js('this') self = _js('self') def flt(stan, quote=True, client=None): """Flatten some stan to a string suitable for embedding in a javascript string. If quote is True, apostrophe, quote, and newline will be quoted """
def cb(result): returner(result) drive() return result def eb(failure): finished.errback(failure) return failure cfac = getCtx('CursorFactory') if cfac: deferred.addCallback(cfac.store.transback, cb).addErrback(cfac.store.transback, eb) else: deferred.addCallback(cb).addErrback(eb) drive() return finished class ContextualClosure(object): __slots__ = ['cell', 'context'] def __init__(self, cell, context): self.cell = cell self.context = context def ContextualClosureSerializer(original, context): return flat.serialize(original.cell, original.context) def DeferredSerializer(original, context): return original.addCallback(lambda r: (flat.serialize(r, context), ContextualClosure(r, context))[1]) flat.registerFlattener(ContextualClosureSerializer, ContextualClosure)