• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python flat.serialize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nevow.flat.serialize函数的典型用法代码示例。如果您正苦于以下问题:Python serialize函数的具体用法?Python serialize怎么用?Python serialize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了serialize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:StetHD,项目名称:nevow,代码行数:31,代码来源:test_loaders.py


示例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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:35,代码来源:flatstan.py


示例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 '&amp;'
                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)
开发者ID:comfuture,项目名称:numbler,代码行数:27,代码来源:url.py


示例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)
开发者ID:UstadMobile,项目名称:exelearning-ustadmobile-work,代码行数:9,代码来源:flatstan.py


示例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)
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:55,代码来源:flatmdom.py


示例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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:7,代码来源:flatstan.py


示例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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:31,代码来源:flatstan.py


示例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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:11,代码来源:appserver.py


示例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'&amp;'
                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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:38,代码来源:url.py


示例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)
开发者ID:KenMacD,项目名称:ldaptor,代码行数:18,代码来源:weave.py


示例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)
开发者ID:comfuture,项目名称:numbler,代码行数:20,代码来源:livepage.py


示例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)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:24,代码来源:flatstan.py


示例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
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:99,代码来源:flatstan.py


示例14: FailureSerializer

def FailureSerializer(original, ctx):
    from nevow import failure

    return serialize(failure.formatFailure(original), ctx)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:4,代码来源:flatstan.py


示例15: DocFactorySerializer

def DocFactorySerializer(original, ctx):
    """Serializer for document factories.
    """
    return serialize(original.load(ctx), ctx)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:4,代码来源:flatstan.py


示例16: CommentSerializer

def CommentSerializer(original, context):
    yield "<!--"
    for x in original.children:
        yield serialize(x, context)
    yield "-->"
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:5,代码来源:flatstan.py


示例17: dnSerializer

def dnSerializer(original, context):
    return flat.serialize(str(original), context)
开发者ID:KenMacD,项目名称:ldaptor,代码行数:2,代码来源:weave.py


示例18: ListSerializer

def ListSerializer(original, context):
    for item in original:
        yield serialize(item, context)
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:3,代码来源:flatstan.py


示例19: flattenJS

def flattenJS(theJS, ctx):
    new = JavascriptContext(ctx, tags.invisible[theJS])
    return flat.serialize(theJS._children, new)
开发者ID:comfuture,项目名称:numbler,代码行数:3,代码来源:livepage.py


示例20: flattenSingleQuote

def flattenSingleQuote(singleQuote, ctx):
    new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString=True)
    return flat.serialize(singleQuote.children, new)
开发者ID:comfuture,项目名称:numbler,代码行数:3,代码来源:livepage.py



注:本文中的nevow.flat.serialize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python flatsax.parseString函数代码示例发布时间:2022-05-27
下一篇:
Python flat.precompile函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap