本文整理汇总了Python中nevow.flat.precompile函数的典型用法代码示例。如果您正苦于以下问题:Python precompile函数的具体用法?Python precompile怎么用?Python precompile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了precompile函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
def load(self, ctx=None):
rendererFactoryClass = None
if ctx is not None:
r = inevow.IRendererFactory(ctx, None)
if r is not None:
rendererFactoryClass = getClass(r)
cacheKey = (self._filename, self.pattern, rendererFactoryClass)
try:
cachedModified, doc = self._cache[cacheKey]
except KeyError:
cachedModified = doc = None
currentModified = os.path.getmtime(self._filename)
if currentModified == cachedModified:
return doc
doc = flatsax.parse(open(self._filename), self.ignoreDocType, self.ignoreComment)
doc = flat.precompile(doc, ctx)
if self.pattern is not None:
doc = inevow.IQ(doc).onePattern(self.pattern)
self._mtime = currentModified
self._cache[cacheKey] = currentModified, doc
return doc
示例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: 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)
示例4: load
def load(self, ctx=None, preprocessors=()):
assert not preprocessors, "preprocessors not supported by htmlstr"
if self._cache is None:
doc = microdom.parseString(self.template, beExtremelyLenient=self.beExtremelyLenient)
doc = flat.precompile(doc, ctx)
if self.pattern is not None:
doc = inevow.IQ(doc).onePattern(self.pattern)
self._cache = doc
return self._cache
示例5: testXML
def testXML(self):
t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href">href</n:attr>label</a>'
result = flat.flatten(loaders.xmlstr(t).load())
self.assertEqual(result, '<a href="href">label</a>')
t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr>label</a>'
ctx = context.WovenContext()
ctx.fillSlots('href', 'href')
result = flat.flatten(flat.precompile(loaders.xmlstr(t).load()), ctx)
self.assertEqual(result, '<a href="href">label</a>')
示例6: testHTML
def testHTML(self):
t = '<a href="#"><nevow:attr name="href">href</nevow:attr>label</a>'
doc = flat.flatten(loaders.htmlstr(t).load())
self.assertEqual(doc, '<a href="href">label</a>')
t = '<a href="#"><nevow:attr name="href"><nevow:slot name="href"/></nevow:attr>label</a>'
ctx = context.WovenContext()
ctx.fillSlots('href', 'href')
precompiled = flat.precompile(loaders.htmlstr(t).load())
result = flat.flatten(precompiled, ctx)
self.assertEqual(result, '<a href="href">label</a>')
示例7: _reallyLoad
def _reallyLoad(self, path, ctx, preprocessors):
doc = flatsax.parse(open(self._filename), self.ignoreDocType, self.ignoreComment)
for proc in preprocessors:
doc = proc(doc)
doc = flat.precompile(doc, ctx)
if self.pattern is not None:
doc = inevow.IQ(doc).onePattern(self.pattern)
return doc
示例8: 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)
示例9: render
def render(self, tag, precompile=False, data=None, setupRequest=lambda r: r, setupContext=lambda c:c, wantDeferred=False):
ctx = self.setupContext(precompile, setupRequest)
ctx = setupContext(ctx)
if precompile:
return flat.precompile(tag, ctx)
else:
if wantDeferred:
L = []
D = twist.deferflatten(tag, ctx, L.append)
D.addCallback(lambda igresult: ''.join(L))
return D
else:
return flat.flatten(tag, ctx)
示例10: test_stanPrecompiled
def test_stanPrecompiled(self):
"""
Test that a stan loader works with precompiled documents.
(This behavior will probably be deprecated soon, but we need to test
that it works right until we remove it.)
"""
doc = flat.precompile(t.ul(id='nav')[t.li['one'], t.li['two'], t.slot('three')])
df = loaders.stan(doc)
loaded = df.load()
self.assertEqual(loaded[0], '<ul id="nav"><li>one</li><li>two</li>')
self.failUnless(isinstance(loaded[1], _PrecompiledSlot))
self.assertEqual(loaded[1].name, 'three')
self.assertEqual(loaded[2], '</ul>')
示例11: render
def render(self, tag, precompile=False, data=None, setupRequest=lambda r: r, setupContext=lambda c:c):
ctx = self.setupContext(precompile, setupRequest)
ctx = setupContext(ctx)
if precompile:
return flat.precompile(tag, ctx)
else:
try:
from twisted.trial import util
from nevow.flat import twist
except ImportError:
return flat.flatten(tag, ctx)
else:
L = []
util.deferredResult(twist.deferflatten(tag, ctx, L.append))
return ''.join(L)
示例12: 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
示例13: test_precompilePatternWithNoChildren
def test_precompilePatternWithNoChildren(self):
tag = tags.img(pattern='item')
pc = flat.precompile(tag)
self.assertEqual(pc[0].tag.children, [])