Ejemplo n.º 1
0
class ExampleElement(Element):
    loader = XMLFile(FilePath('templates/tpl_temperature.xml'))

    
    def __init__(self, temp,  hum):
        self.temperature = temp
        self.hummidity = hum
        self.extraTemperatureContent = XMLString('<input id="temperature" type="range" min="-100" max="100" value="'+self.temperature+'" class="xwot1 sensor columns large-8" />')
        self.extraHumidityContent = XMLString('<input id="humidity" type="range" min="0" max="100" value="'+self.hummidity+'" class="xwot1 sensor columns large-8" />')

    @renderer
    def header(self, request, tag):
        return tag('Header.')
        
    @renderer
    def temp(self, request, tag):
        return self.temperature
        
    @renderer
    def temperatureInput(self,  request,  tag):
        return self.extraTemperatureContent.load()

    @renderer
    def humidity(self, request, tag):
        return self.hummidity
        
    @renderer
    def humidityInput(self,  request,  tag):
        return self.extraHumidityContent.load()
 def render_content(self, request, tag):
     """
     render the content for the graph container
     """
     if self.showreel_document is not None:
         graph_row_xml = XMLString(self.get_content_xml())
         return graph_row_xml.load()
     else:
         oops_container = self.get_bad_container()
         return oops_container.load()
    def configuration_content(self, request, tag):
        """
        """
        set_theme = theme_helpers.get_configured_theme(self.accessor)
        set_style = theme_helpers.get_configured_style(self.accessor)
        output_string = ""
        output_string += "<div>"
        output_string += "<h3>Themes</h3>"
        output_string += '<div class="btn-group">'

        for theme in theme_helpers.get_configured_themes():
            if theme == set_theme:
                output_string += (
                    "<button type=\"button\" onclick=\"setTheme"
                    "('%s')\" class=\"%s\">%s</button>" % (
                        theme,
                        "btn btn-primary",
                        theme
                    ))
            else:
                output_string += (
                    "<button type=\"button\" onclick=\"setTheme"
                    "('%s')\" class=\"%s\">%s</button>" % (
                        theme,
                        "btn btn-default",
                        theme
                    ))

        output_string += "</div>"

        output_string += "<h3>Colour Schemes</h3>"
        output_string += '<div class="btn-group">'
        for style in theme_helpers.get_configured_styles():
            if style == set_style:
                output_string += (
                    "<button type=\"button\" onclick=\"setStyle"
                    "('%s')\" class=\"%s\">%s</button>" % (
                        style,
                        "btn btn-primary",
                        style
                    ))
            else:
                output_string += (
                    "<button type=\"button\" onclick=\"setStyle"
                    "('%s')\" class=\"%s\">%s</button>" % (
                        style,
                        "btn btn-default",
                        style
                    ))

        output_string += "</div>"
        output_string += "</div>"
        renderable_string = XMLString(output_string)
        return renderable_string.load()
Ejemplo n.º 4
0
 def render_content(self, request, tag):
     """
     render the content for the graph container
     """
     try:
         graph_row_xml = XMLString(self.get_row_xml())
         return graph_row_xml.load()
     except Exception as err:
         logging.error(
             "Exception raised when rendering graphs, exception: %r" % (
                 err, ))
         oops_container = self.get_bad_container()
         return oops_container.load()
Ejemplo n.º 5
0
 def loadMessage(self, code):
     tag = XMLString(
         ('<t:transparent xmlns:t="http://twistedmatrix.com/'
          'ns/twisted.web.template/0.1">') +
         ERROR_MESSAGES.get(code, "") +
         '</t:transparent>').load()[0]
     return tag
class Elem(Element):
    loader = XMLString(b"""
        <div xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
        """ + b"A" * 1000 + b"""
        <div t:render="r" />
        <div t:render="r2" />
        <div t:render="r3">
        <t:slot name="meep" />
        </div>
        </div>
        """)

    def __init__(self, children=[]):
        super(Elem, self).__init__()
        self.children = children

    @renderer
    def r(self, req, tag):
        return tag([self.children, u'hi mom!'], attr=u'value')

    @renderer
    def r2(self, req, tag):
        return tags.div(u'foo', attr=u'value')

    @renderer
    def r3(self, req, tag):
        return tag.fillSlots(meep=(u'slotvalue', u'42', b'bar',
                                   tags.div(u'meep', attr=u'value')))
Ejemplo n.º 7
0
 def test_entityConversion(self):
     """
     When flattening an HTML entity, it should flatten out to the utf-8
     representation if possible.
     """
     element = Element(loader=XMLString('<p>&#9731;</p>'))
     return self.assertFlattensTo(element, b'<p>\xe2\x98\x83</p>')
Ejemplo n.º 8
0
 def test_entityConversion(self):
     """
     When flattening an HTML entity, it should flatten out to the utf-8
     representation if possible.
     """
     element = Element(loader=XMLString("<p>&#9731;</p>"))
     self.assertFlattensImmediately(element, b"<p>\xe2\x98\x83</p>")
Ejemplo n.º 9
0
class MenuNavigationBar(Element):
    '''
    Convenient class to create a dynamic navigation bar

    .. versionadded:: 0.8.2

    .. note:: This is strongly related with the file:
              templates/template_index.html. The content of the each element
              should be implemented dynamically (here or in any subclass) or
              statically (into the mentioned file).
    '''
    loader = XMLString(template_menu_item)
    menuData = ['cohen3', 'devices', 'logging', 'about']

    def __init__(self, page):
        super(MenuNavigationBar, self).__init__()
        self.page = page
        self.coherence = page.coherence
        self.tabs = []

    @renderer
    def menu_elements(self, request, tag):
        for el in self.menuData:
            link = el.lower()
            cls_active = ''
            if el == 'cohen3':
                link = 'home'
                cls_active += 'active'
            tag.fillSlots(menu_id=f'but-{link}')
            tag.fillSlots(menu_class=f'{cls_active}')
            tag.fillSlots(menu_click=f'openTab(\'{link}\', this)')
            yield MenuItemElement(TagLoader(tag), el)
Ejemplo n.º 10
0
    def test_elementContainingDynamicElement(self):
        """
        Directives in the document factory of an Element returned from a render
        method of another Element are satisfied from the correct object: the
        "inner" Element.
        """
        class OuterElement(Element):
            @renderer
            def outerMethod(self, request, tag):
                return tag(
                    InnerElement(loader=XMLString("""
                <t:ignored
                  xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
                  t:render="innerMethod" />
                """)))

        class InnerElement(Element):
            @renderer
            def innerMethod(self, request, tag):
                return "Hello, world."

        element = OuterElement(loader=XMLString("""
        <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
          t:render="outerMethod" />
        """))
        return self.assertFlattensTo(element, b"<p>Hello, world.</p>")
Ejemplo n.º 11
0
    def test_sameLoaderTwice(self):
        """
        Rendering the output of a loader, or even the same element, should
        return different output each time.
        """
        sharedLoader = XMLString(
            '<p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">'
            '<t:transparent t:render="classCounter" /> '
            '<t:transparent t:render="instanceCounter" />'
            '</p>')

        class DestructiveElement(Element):
            count = 0
            instanceCount = 0
            loader = sharedLoader

            @renderer
            def classCounter(self, request, tag):
                DestructiveElement.count += 1
                return tag(str(DestructiveElement.count))
            @renderer
            def instanceCounter(self, request, tag):
                self.instanceCount += 1
                return tag(str(self.instanceCount))

        e1 = DestructiveElement()
        e2 = DestructiveElement()
        self.assertFlattensImmediately(e1, b"<p>1 1</p>")
        self.assertFlattensImmediately(e1, b"<p>2 2</p>")
        self.assertFlattensImmediately(e2, b"<p>3 1</p>")
Ejemplo n.º 12
0
 def outerMethod(self, request, tag):
     return tag(
         InnerElement(loader=XMLString("""
     <t:ignored
       xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="innerMethod" />
     """)))
Ejemplo n.º 13
0
def html2stan(html):
    """
    Convert an HTML string to a Stan tree.

    @param html: An HTML fragment; multiple roots are allowed.
    @type html: C{string}
    @return: The fragment as a tree with a transparent root node.
    """
    if isinstance(html, str):
        html = html.encode('utf8')

    html = _RE_CONTROL.sub(lambda m:b'\\x%02x' % ord(m.group()), html)
    stan = XMLString(b'<div>%s</div>' % html).load()[0]
    assert stan.tagName == 'div'
    stan.tagName = ''
    return stan
Ejemplo n.º 14
0
Archivo: web.py Proyecto: tazjel/bravo
class BravoRootElement(Element):
    """
    Element representing the web site root.
    """

    loader = XMLString(root_template)

    def __init__(self, worlds, services):
        Element.__init__(self)
        self.services = services
        self.worlds = worlds

    @renderer
    def title(self, request, tag):
        return tag("Bravo %s" % version)

    @renderer
    def service(self, request, tag):
        services = []
        for name, factory in self.services.iteritems():
            services.append(tags.li("%s (%s)" % (name, factory.__class__)))
        return tag(tags.h2("Services"), tags.ul(*services))

    @renderer
    def world(self, request, tag):
        worlds = []
        for name in self.worlds.keys():
            worlds.append(tags.li(tags.a(name.title(), href=name)))
        return tag(tags.h2("Worlds"), tags.ul(*worlds))
Ejemplo n.º 15
0
 def outerMethod(self, request: Optional[IRequest],
                 tag: Tag) -> Flattenable:
     return tag(
         InnerElement(loader=XMLString("""
     <t:ignored
       xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="innerMethod" />
     """)))
Ejemplo n.º 16
0
class TestElement(Element):
    """
    An L{Element} that can be rendered successfully.
    """
    loader = XMLString(
        '<p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">'
        'Hello, world.'
        '</p>')
    def configuration_content(self, request, tag):
        """
        get the list content
        """
        output_string = ""
        output_string += '<div class="list-group">'
        output_string += "<div>"

        output_string += self.get_showreel_xml()
        output_string += self.get_dashboard_xml()
        output_string += self.get_graph_xml()
        output_string += self.get_data_sources_xml()

        output_string += "</div>"
        output_string += "</div>"
        renderable_string = XMLString(output_string)
        return renderable_string.load()
Ejemplo n.º 18
0
 def __init__(self, name: str, text: str):
     super().__init__(name=name, text=text)
     if self.is_empty():
         self._dom: Optional[minidom.Document] = None
         self._version = -1
         self._loader: ITemplateLoader = TagLoader(tags.transparent)
     else:
         self._dom = parse_xml(self.text)
         self._version = self._extract_version(self._dom, self.name)
         self._loader = XMLString(self._dom.toxml())
Ejemplo n.º 19
0
class AutomatonStatsElement(Element):
    """
    Render some information about automatons.
    """

    loader = XMLString(automaton_stats_template)

    @renderer
    def main(self, request, tag):
        return tag(*(AutomatonElement(a) for a in factory.automatons))
Ejemplo n.º 20
0
 def test_lenientPrefixBehavior(self):
     """
     If the parser sees a prefix it doesn't recognize on an attribute, it
     will pass it on through to serialization.
     """
     theInput = ('<hello:world hello:sample="testing" '
                 'xmlns:hello="http://made-up.example.com/ns/not-real">'
                 "This is a made-up tag.</hello:world>")
     element = Element(loader=XMLString(theInput))
     self.assertFlattensTo(element, theInput.encode("utf8"))
Ejemplo n.º 21
0
class RecentChangesElement(Element):

    def __init__(self, root):
        self.root = root

    @renderer
    def changes(self, request, tag):
        r = []
        for d in reversed(self.root._edits):
            r.append(
                tag.clone().fillSlots(
                    diff=self.diff(d, request),
                    hist=self.hist(d, request),
                    object=util.taglink(d.obj),
                    time=d.time,
                    user=d.user))
        return r

    def diff(self, data, request):
        u = URLPath.fromRequest(request)
        u = u.sibling('diff')
        u.query = urllib.urlencode({
            'ob': data.obj.fullName(),
            'revA': data.rev-1,
            'revB': data.rev,
            })
        return tags.a(href=str(u))("(diff)")

    def hist(self, data, request):
        u = URLPath.fromRequest(request)
        u = u.sibling('diff')
        u.query = urllib.urlencode({
            'ob': data.obj.fullName(),
            'rev': data.rev,
            })
        return tags.a(href=str(u))("(hist)")

    loader = XMLString('''\
    <html xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
    <head>
    <title>Recent Changes</title>
    <link rel="stylesheet" type="text/css" href="apidocs.css" />
    </head>
    <body>
    <h1>Recent Changes</h1>
    <p>See <a href="bigDiff">a diff containing all changes made online</a></p>
    <ul>
    <li t:render="changes">
    <t:slot name="diff" /> - <t:slot name="hist" /> - <t:slot name="object" />
    - <t:slot name="time" /> - <t:slot name="user" /> 
    </li>
    </ul>
    </body>
    </html>
    ''')
Ejemplo n.º 22
0
class SimpleElement(Element):
    loader = XMLString(
        '<h1 xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1" '
        't:render="name" />')

    def __init__(self, name):
        self._name = name

    @renderer
    def name(self, request, tag):
        return tag(self._name)
Ejemplo n.º 23
0
 def test_transparentRendering(self):
     """
     A C{transparent} element should be eliminated from the DOM and rendered as
     only its children.
     """
     element = Element(loader=XMLString(
         "<t:transparent "
         'xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">'
         "Hello, world."
         "</t:transparent>"))
     return self.assertFlattensTo(element, b"Hello, world.")
Ejemplo n.º 24
0
 def test_missingRenderMethod(self):
     """
     Flattening an L{Element} with a C{loader} which has a tag with a render
     directive fails with L{FlattenerError} if there is no available render
     method to satisfy that directive.
     """
     element = Element(loader=XMLString("""
     <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="unknownMethod" />
     """))
     return self.assertFlatteningRaises(element, MissingRenderMethod)
Ejemplo n.º 25
0
 def test_attrRendering(self):
     """
     An Element with an attr tag renders the vaule of its attr tag as an
     attribute of its containing tag.
     """
     element = Element(loader=XMLString(
         '<a xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">'
         '<t:attr name="href">http://example.com</t:attr>'
         "Hello, world."
         "</a>"))
     return self.assertFlattensTo(
         element, b'<a href="http://example.com">Hello, world.</a>')
Ejemplo n.º 26
0
class TestFailureElement(Element):
    """
    An L{Element} that can be used in place of L{FailureElement} to verify
    that L{renderElement} can render failures properly.
    """
    loader = XMLString(
        '<p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">'
        'I failed.'
        '</p>')

    def __init__(self, failure, loader=None):
        self.failure = failure
Ejemplo n.º 27
0
class RoomsElement(Element):

    loader = XMLString(
        ('<h1 '
         'xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"'
         '>Hello, <span t:render="name"></span>!</h1>'))

    def __init__(self, name):
        self.m_name = name

    @renderer
    def name(self, _request, _tag):
        return self.m_name
Ejemplo n.º 28
0
def rstToStan(rst):
    html = rstToHTML(rst)
    # fix a bad encoding in docutils
    html = html.replace('encoding="unicode"', '')
    stan = XMLString(html).load()[0]
    if stan.tagName != "html":
        raise ValueError("Unexpected top-level HTML tag.")
    head, body = [x for x in stan.children if checkTag(x)]
    if head.tagName != "head":
        raise ValueError("Expected 'head' node, got '%s'" % (head.tagName))
    if body.tagName != "body":
        raise ValueError("Expected 'body' node, got '%s'" % (body.tagName))
    return body.children
Ejemplo n.º 29
0
class BravoElement(Element):

    loader = XMLString(root_template)

    def __init__(self, services):
        Element.__init__(self)

        self.services = services

    @renderer
    def title(self, request, tag):
        return tag("Bravo %s" % version)

    @renderer
    def service(self, request, tag):
        l = []
        services = []
        for name, service in self.services.iteritems():
            factory = service.args[1]
            if isinstance(factory, BravoFactory):
                services.append(self.bravofactory(request, tags.div, factory))
            else:
                l.append(
                    tags.li("%s (%s)" % (name, self.services[name].__class__)))
        ul = tags.ul(*l)
        div = tags.div(*services)
        return tag(ul, div)

    def bravofactory(self, request, tag, factory):
        g = (tags.li(username) for username in factory.protocols)
        users = tags.div(tags.h3("Users"), tags.ul(*g))
        world = self.world(request, tags.div, factory.world)
        return tag(tags.h2("Bravo world %s" % factory.name), users, world)

    def world(self, request, tag, world):
        l = []
        total = (len(world.chunk_cache) + len(world.dirty_chunk_cache) +
                 len(world._pending_chunks))
        l.append(tags.li("Total chunks: %d" % total))
        l.append(tags.li("Clean chunks: %d" % len(world.chunk_cache)))
        l.append(tags.li("Dirty chunks: %d" % len(world.dirty_chunk_cache)))
        l.append(
            tags.li("Chunks being generated: %d" % len(world._pending_chunks)))
        if world.permanent_cache:
            l.append(
                tags.li("Permanent cache: enabled, %d chunks" %
                        len(world.permanent_cache)))
        else:
            l.append(tags.li("Permanent cache: disabled"))
        status = tags.ul(*l)
        return tag(tags.h3("World status"), status)
Ejemplo n.º 30
0
class BravoWorldElement(Element):
    """
    Element representing a single world.
    """

    loader = XMLString(world_template)

    def __init__(self, factory, plugins):
        Element.__init__(self)
        self.factory = factory
        self.plugins = plugins

    @renderer
    def title(self, request, tag):
        return tag("World %s" % self.factory.name.title())

    @renderer
    def user(self, request, tag):
        users = (tags.li(username) for username in self.factory.protocols)
        return tag(tags.h2("Users"), tags.ul(*users))

    @renderer
    def status(self, request, tag):
        world = self.factory.world
        l = []
        total = (len(world.chunk_cache) + len(world.dirty_chunk_cache) +
                 len(world._pending_chunks))
        l.append(tags.li("Total chunks: %d" % total))
        l.append(tags.li("Clean chunks: %d" % len(world.chunk_cache)))
        l.append(tags.li("Dirty chunks: %d" % len(world.dirty_chunk_cache)))
        l.append(
            tags.li("Chunks being generated: %d" % len(world._pending_chunks)))
        if world.permanent_cache:
            l.append(
                tags.li("Permanent cache: enabled, %d chunks" %
                        len(world.permanent_cache)))
        else:
            l.append(tags.li("Permanent cache: disabled"))
        status = tags.ul(*l)
        return tag(tags.h2("Status"), status)

    @renderer
    def plugin(self, request, tag):
        plugins = []
        for name in self.plugins.keys():
            plugins.append(
                tags.li(
                    tags.a(name.title(),
                           href='%s/%s' % (self.factory.name, name))))
        return tag(tags.h2("Plugins"), tags.ul(*plugins))
Ejemplo n.º 31
0
 def test_elementContainingStaticElement(self):
     """
     An Element which is returned by the render method of another Element is
     rendered properly.
     """
     class RenderfulElement(Element):
         @renderer
         def renderMethod(self, request, tag):
             return tag(Element(
                 loader=XMLString("<em>Hello, world.</em>")))
     element = RenderfulElement(loader=XMLString("""
     <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="renderMethod" />
     """))
     return self.assertFlattensTo(element, b"<p><em>Hello, world.</em></p>")
Ejemplo n.º 32
0
 def test_directiveRenderingOmittingTag(self):
     """
     An Element with a render method which omits the containing tag
     successfully removes that tag from the output.
     """
     class RenderfulElement(Element):
         @renderer
         def renderMethod(self, request, tag):
             return "Hello, world."
     element = RenderfulElement(loader=XMLString("""
     <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="renderMethod">
         Goodbye, world.
     </p>
     """))
     return self.assertFlattensTo(element, b"Hello, world.")
Ejemplo n.º 33
0
 def test_directiveRendering(self):
     """
     An Element with a valid render directive has that directive invoked and
     the result added to the output.
     """
     renders = []
     class RenderfulElement(Element):
         @renderer
         def renderMethod(self, request, tag):
             renders.append((self, request))
             return tag("Hello, world.")
     element = RenderfulElement(loader=XMLString("""
     <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="renderMethod" />
     """))
     return self.assertFlattensTo(element, b"<p>Hello, world.</p>")
Ejemplo n.º 34
0
 def test_deferredRendering(self):
     """
     An Element with a render method which returns a Deferred will render
     correctly.
     """
     class RenderfulElement(Element):
         @renderer
         def renderMethod(self, request, tag):
             return succeed("Hello, world.")
     element = RenderfulElement(loader=XMLString("""
     <p xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"
       t:render="renderMethod">
         Goodbye, world.
     </p>
     """))
     return self.assertFlattensTo(element, b"Hello, world.")
Ejemplo n.º 35
0
def html2stan(html):
    """
    Convert HTML to a Stan structure.

    @param html: A HTML string.
    @type html: L{unicode} or L{bytes}
    """
    if isinstance(html, unicode):
        html = html.encode("utf8")

    html = _control_pat.sub(lambda m: "\\x%02x" % ord(m.group()), html)
    html = "<div>" + html + "</div>"
    html = XMLString(html).load()[0].children
    if html and html[-1] == u"\n":
        del html[-1]
    return html
Ejemplo n.º 36
0
 def __init__(self, temp,  hum):
     self.temperature = temp
     self.hummidity = hum
     self.extraTemperatureContent = XMLString('<input id="temperature" type="range" min="-100" max="100" value="'+self.temperature+'" class="xwot1 sensor columns large-8" />')
     self.extraHumidityContent = XMLString('<input id="humidity" type="range" min="0" max="100" value="'+self.hummidity+'" class="xwot1 sensor columns large-8" />')