本文整理汇总了Python中nevow.flat.serialize函数的典型用法代码示例。如果您正苦于以下问题:Python serialize函数的具体用法?Python serialize怎么用?Python serialize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了serialize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_reloadAfterPrecompile
def test_reloadAfterPrecompile(self):
"""
"""
# Get a filename
temp = self.mktemp()
# Write some content
f = file(temp, 'w')
f.write('<p>foo</p>')
f.close()
# Precompile the doc
ctx = context.WovenContext()
doc = loaders.htmlfile(temp)
pc = flat.precompile(flat.flatten(doc), ctx)
before = ''.join(flat.serialize(pc, ctx))
# Write the file with different content and make sure the
# timestamp changes
f = file(temp, 'w')
f.write('<p>bar</p>')
f.close()
os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5))
after = ''.join(flat.serialize(pc, ctx))
self.assertIn('foo', before)
self.assertIn('bar', after)
self.failIfEqual(before, after)
示例2: SlotSerializer
def SlotSerializer(original, context):
"""
Serialize a slot.
If the value is already available in the given context, serialize and
return it. Otherwise, if this is a precompilation pass, return a new
kind of slot which captures the current render context, so that any
necessary quoting may be performed. Otherwise, raise an exception
indicating that the slot cannot be serialized.
"""
if context.precompile:
try:
data = context.locateSlotData(original.name)
except KeyError:
return _PrecompiledSlot(
original.name,
precompile(original.children, context),
original.default,
context.isAttrib,
context.inURL,
context.inJS,
context.inJSSingleQuoteString,
original.filename,
original.lineNumber,
original.columnNumber,
)
else:
return serialize(data, context)
try:
data = context.locateSlotData(original.name)
except KeyError:
if original.default is None:
raise
data = original.default
return serialize(data, context)
示例3: URLSerializer
def URLSerializer(original, context):
urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
if original.scheme:
yield "%s://%s" % (original.scheme, original.netloc)
for pathsegment in original._qpathlist:
yield '/'
yield serialize(pathsegment, urlContext)
query = original._querylist
if query:
yield '?'
first = True
for key, value in query:
if not first:
# xhtml can't handle unescaped '&'
if context.isAttrib is True:
yield '&'
else:
yield '&'
else:
first = False
yield serialize(key, urlContext)
if value is not None:
yield '='
yield serialize(value, urlContext)
if original.fragment:
yield "#"
yield serialize(original.fragment, urlContext)
示例4: inlineJSSerializer
def inlineJSSerializer(original, ctx):
from nevow import livepage
from nevow.tags import script, xml
theJS = livepage.js(original.children)
new = livepage.JavascriptContext(ctx, invisible[theJS])
return serialize(script(type="text/javascript")[
xml('\n//<![CDATA[\n'),
serialize(theJS, new),
xml('\n//]]>\n')], ctx)
示例5: MicroDomElementSerializer
def MicroDomElementSerializer(element, context):
directiveMapping = {
'render': 'render',
'data': 'data',
'macro': 'macro',
}
attributeList = [
'pattern', 'key',
]
name = element.tagName
if name.startswith('nevow:'):
_, name = name.split(':')
if name == 'invisible':
name = ''
elif name == 'slot':
return slot(element.attributes['name'])[
precompile(serialize(element.childNodes, context), context)]
attrs = dict(element.attributes) # get rid of CaseInsensitiveDict
specials = {}
attributes = attributeList
directives = directiveMapping
for k, v in attrs.items():
# I know, this is totally not the way to do xml namespaces but who cares right now
## I'll fix it later
if not k.startswith('nevow:'):
continue
_, nons = k.split(':')
if nons in directives:
## clean this up by making the names more consistent
specials[directives[nons]] = directive(v)
del attrs[k]
if nons in attributes:
specials[nons] = v
del attrs[k]
# TODO: there must be a better way than this ...
# Handle any nevow:attr elements. If we don't do it now then this tag will
# be serialised and it will too late.
childNodes = []
for child in element.childNodes:
if getattr(child,'tagName',None) == 'nevow:attr':
attrs[child.attributes['name']] = child.childNodes
else:
childNodes.append(child)
tag = Tag(
name,
attributes=attrs,
children=childNodes,
specials=specials
)
return serialize(tag, context)
示例6: DirectiveSerializer
def DirectiveSerializer(original, context):
if context.precompile:
return original
rendererFactory = context.locate(IRendererFactory)
renderer = rendererFactory.renderer(context, original.name)
return serialize(renderer, context)
示例7: PrecompiledSlotSerializer
def PrecompiledSlotSerializer(original, context):
"""
Serialize a pre-compiled slot.
Return the serialized value of the slot or raise a KeyError if it has no
value.
"""
# Precompilation should _not_ be happening at this point, but Nevow is very
# sloppy about precompiling multiple times, so sometimes we are in a
# precompilation context. In this case, there is nothing to do, just
# return the original object. The case which seems to exercise this most
# often is the use of a pattern as the stan document given to the stan
# loader. The pattern has already been precompiled, but the stan loader
# precompiles it again. This case should be eliminated by adding a loader
# for precompiled documents.
if context.precompile:
warnings.warn("[v0.9.9] Support for multiple precompilation passes is deprecated.", PendingDeprecationWarning)
return original
try:
data = context.locateSlotData(original.name)
except KeyError:
if original.default is None:
raise
data = original.default
originalContext = context.clone(deep=False)
originalContext.isAttrib = original.isAttrib
originalContext.inURL = original.inURL
originalContext.inJS = original.inJS
originalContext.inJSSingleQuoteString = original.inJSSingleQuoteString
return serialize(data, originalContext)
示例8: renderInlineException
def renderInlineException(self, context, reason):
from nevow import failure
formatted = failure.formatFailure(reason)
desc = str(reason)
return flat.serialize([
stan.xml("""<div style="border: 1px dashed red; color: red; clear: both" onclick="this.childNodes[1].style.display = this.childNodes[1].style.display == 'none' ? 'block': 'none'">"""),
desc,
stan.xml('<div style="display: none">'),
formatted,
stan.xml('</div></div>')
], context)
示例9: URLSerializer
def URLSerializer(original, context):
"""
Serialize the given L{URL}.
Unicode path, query and fragment components are handled according to the
IRI standard (RFC 3987).
"""
def _maybeEncode(s):
if isinstance(s, str):
s = s.encode('utf-8')
return s
urlContext = WovenContext(parent=context, precompile=context.precompile, inURL=True)
if original.scheme:
# TODO: handle Unicode (see #2409)
yield b"%s://%s" % (toBytes(original.scheme), toBytes(original.netloc))
for pathsegment in original._qpathlist:
yield b'/'
yield serialize(_maybeEncode(pathsegment), urlContext)
query = original._querylist
if query:
yield b'?'
first = True
for key, value in query:
if not first:
# xhtml can't handle unescaped '&'
if context.isAttrib is True:
yield b'&'
else:
yield b'&'
else:
first = False
yield serialize(_maybeEncode(key), urlContext)
if value is not None:
yield b'='
yield serialize(_maybeEncode(value), urlContext)
if original.fragment:
yield b"#"
yield serialize(_maybeEncode(original.fragment), urlContext)
示例10: entrySerializer
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()
li[liul]
for i in l:
liul[tags.li[i]]
return flat.serialize(ul, context)
示例11: flattenAttemptDeferred
def flattenAttemptDeferred(d, ctx):
def attemptComplete(ctx, result, reason=None):
if result == 'success':
d.callback(None)
else:
d.errback(ClientSideException(reason))
transient = IClientHandle(ctx).transient(attemptComplete)
return flat.serialize([
_js("""try {
"""),
d.stuff,
_js("""
"""),
transient('success'),
_js("""
} catch (e) {
"""),
transient('failure', js.e),
_js("}")
], ctx)
示例12: FunctionSerializer
def FunctionSerializer(original, context, nocontextfun=FunctionSerializer_nocontext):
if context.precompile:
return WovenContext(tag=invisible(render=original))
else:
data = convertToData(context.locate(IData), context)
try:
nocontext = nocontextfun(original)
if nocontext is True:
if hasattr(original, "__code__") and (
original.__code__.co_argcount == 3
or (original.__code__.co_argcount == 2 and original.__code__.co_varnames[0] != "self")
):
result = original(context, data)
else:
result = original(data)
else:
if nocontext is PASS_SELF:
renderer = context.locate(IRenderer)
result = original(renderer, context, data)
else:
result = original(context, data)
except StopIteration:
raise RuntimeError("User function %r raised StopIteration." % original)
return serialize(result, context)
示例13: TagSerializer
def TagSerializer(original, context, contextIsMine=False):
"""
Original is the tag.
Context is either:
- the context of someone up the chain (if contextIsMine is False)
- this tag's context (if contextIsMine is True)
"""
# print "TagSerializer:",original, "ContextIsMine",contextIsMine, "Context:",context
visible = bool(original.tagName)
if visible and context.isAttrib:
raise RuntimeError("Tried to render tag '%s' in an tag attribute context." % (original.tagName))
if context.precompile and original.macro:
toBeRenderedBy = original.macro
## Special case for directive; perhaps this could be handled some other way with an interface?
if isinstance(toBeRenderedBy, directive):
toBeRenderedBy = IMacroFactory(context).macro(context, toBeRenderedBy.name)
original.macro = Unset
newContext = WovenContext(context, original)
yield serialize(toBeRenderedBy(newContext), newContext)
return
## TODO: Do we really need to bypass precompiling for *all* specials?
## Perhaps just render?
if context.precompile and (
[x for x in list(original._specials.values()) if x is not None and x is not Unset] or original.slotData
):
## The tags inside this one get a "fresh" parent chain, because
## when the context yielded here is serialized, the parent
## chain gets reconnected to the actual parents at that
## point, since the render function here could change
## the actual parentage hierarchy.
nestedcontext = WovenContext(precompile=context.precompile, isAttrib=context.isAttrib)
# If necessary, remember the MacroFactory onto the new context chain.
macroFactory = IMacroFactory(context, None)
if macroFactory is not None:
nestedcontext.remember(macroFactory, IMacroFactory)
original = original.clone(deep=False)
if not contextIsMine:
context = WovenContext(context, original)
context.tag.children = precompile(context.tag.children, nestedcontext)
yield context
return
## Don't render patterns
if original.pattern is not Unset and original.pattern is not None:
return
if not contextIsMine:
if original.render:
### We must clone our tag before passing to a render function
original = original.clone(deep=False)
context = WovenContext(context, original)
if original.data is not Unset:
newdata = convertToData(original.data, context)
if isinstance(newdata, util.Deferred):
yield newdata.addCallback(lambda newdata: _datacallback(newdata, context))
else:
_datacallback(newdata, context)
if original.render:
## If we have a render function we want to render what it returns,
## not our tag
toBeRenderedBy = original.render
# erase special attribs so if the renderer returns the tag,
# the specials won't be on the context twice.
original._clearSpecials()
yield serialize(toBeRenderedBy, context)
return
if not visible:
for child in original.children:
yield serialize(child, context)
return
yield "<%s" % original.tagName
if original.attributes:
attribContext = WovenContext(parent=context, precompile=context.precompile, isAttrib=True)
for (k, v) in sorted(original.attributes.items()):
if v is None:
continue
yield ' %s="' % k
yield serialize(v, attribContext)
yield '"'
if not original.children:
if original.tagName in allowSingleton:
yield " />"
else:
yield "></%s>" % original.tagName
else:
yield ">"
for child in original.children:
yield serialize(child, context)
yield "</%s>" % original.tagName
示例14: FailureSerializer
def FailureSerializer(original, ctx):
from nevow import failure
return serialize(failure.formatFailure(original), ctx)
示例15: DocFactorySerializer
def DocFactorySerializer(original, ctx):
"""Serializer for document factories.
"""
return serialize(original.load(ctx), ctx)