Пример #1
0
 def render_GET(self, request):
     email = self.getRequestEmail(request)
     request.setHeader('content-type', 'text/html; charset=utf-8')
     element = tags.html(
         htmlHead,
         tags.body(tags.form(
             tags.fieldset(
                 tags.div(
                     tags.label('Cert e-mail'),
                     tags.label('Username', for_='username'),
                     tags.label('Password', for_='password'),
                     tags.label('Site', for_='site', class_='last'),
                     id='names',
                 ),
                 tags.div(
                     tags.input(disabled='true', value=email),
                     tags.input(name='username', type='text'),
                     tags.input(name='password', type='password'),
                     tags.input(name='site', type='url', class_='last'),
                     id='fields',
                 ),
             ),
             tags.button('Generate', type='submit'),
             action='', method='POST',
         )),
     )
     return renderElement(request, element)
Пример #2
0
 def customFormRender(self, form):
     # type: (RenderableForm) -> Any
     """
     Include just the glue necessary for CSRF protection and let the
     application render the rest of the form.
     """
     return Element(loader=TagLoader(tags.html(tags.body(form.glue()))))
Пример #3
0
 def test_nestedTags(self):
     """
     Test that nested tags flatten correctly.
     """
     return self.assertFlattensTo(
         tags.html(tags.body('42'), hi='there'),
         '<html hi="there"><body>42</body></html>')
Пример #4
0
def _renderHTTP_exception(request, failure):
    try:
        text, code = humanize_failure(failure)
    except:
        log.msg("exception in humanize_failure")
        log.msg("argument was %s" % (failure, ))
        log.err()
        text = str(failure)
        code = None

    if code is not None:
        return _renderHTTP_exception_simple(request, text, code)

    accept = request.getHeader("accept")
    if not accept:
        accept = "*/*"
    if "*/*" in accept or "text/*" in accept or "text/html" in accept:
        request.setResponseCode(http.INTERNAL_SERVER_ERROR)
        return template.renderElement(
            request,
            tags.html(
                tags.head(tags.title(u"Exception"), ),
                tags.body(FailureElement(failure), ),
            ),
        )

    # use plain text
    traceback = failure.getTraceback()
    return _renderHTTP_exception_simple(
        request,
        traceback,
        http.INTERNAL_SERVER_ERROR,
    )
Пример #5
0
 def test_nestedTags(self):
     """
     Test that nested tags flatten correctly.
     """
     return self.assertFlattensTo(
         tags.html(tags.body('42'), hi='there'),
         '<html hi="there"><body>42</body></html>')
Пример #6
0
 def test_nestedTags(self):
     """
     Test that nested tags flatten correctly.
     """
     self.assertFlattensImmediately(
         tags.html(tags.body("42"), hi="there"),
         b'<html hi="there"><body>42</body></html>',
     )
Пример #7
0
    def render_GET(self, request):
        applications = []
        for app in self.registry.applications.values():
            link = tags.a(tags.tt(app.name), ' at ', tags.tt(app.path.path),
                          href=app.name)
            applications.append(tags.li(link))

        body = tags.body(
            tags.p('Here are your applications:'),
            tags.ul(*applications))
        return renderElement(request, body)
Пример #8
0
    def render_GET(self, request):
        applications = []
        for app in self.registry.applications.values():
            link = tags.a(tags.tt(app.name),
                          ' at ',
                          tags.tt(app.path.path),
                          href=app.name)
            applications.append(tags.li(link))

        body = tags.body(tags.p('Here are your applications:'),
                         tags.ul(*applications))
        return renderElement(request, body)
Пример #9
0
 def render_POST(self, request):
     request.setHeader('content-type', 'text/html; charset=utf-8')
     app = self.getApplication(request)
     password = app.config.generate_for_site(
         request.args['username'][0],
         request.args['password'][0],
         request.args['site'][0])
     element = tags.html(
         htmlHead,
         tags.body(tags.div(
             tags.input(
                 size='1', value=password, onFocus=selectJS, onMouseUp='return false',
             ),
         ), class_='center'),
     ),
     return renderElement(request, element)
class SimpleFeedAggregation(object):
    application = Klein()
    common_page = Plating(tags=tags.html(
        tags.head(tags.title('Feed Aggregator 1.0')),
        tags.body(tags.div(slot(Plating.CONTENT))),
    ))

    def __init__(self, reactor, feed_urls):
        self._reactor = reactor
        self._feed_urls = feed_urls

    @defer.inlineCallbacks
    def retrieve_field(self, url):
        response = yield treq.get(url, timeout=30.0, reactor=self._reactor)
        if response.code != http.OK:
            fail_reason = http.RESPONSES[response.code]
            raise RuntimeError(f'Failed: {response.code} {fail_reason}')
        content = yield response.content()
        defer.returnValue(feedparser.parse(content))

    @common_page.routed(application.route('/'),
                        tags.div(render='feeds:list')(slot('item')))
    def feeds(self, request):
        def render_feed(feed):
            feed_title = feed[u'feed'][u'title']
            feed_link = feed[u'feed'][u'link']
            return tags.table(
                tags.tr(tags.th(tags.a(feed_title, href=feed_link))))([
                    tags.tr(
                        tags.td(tags.a(entry[u'title'], href=entry[u'link'])))
                    for entry in feed[u'entries']
                ])

        return {
            u'feeds': [
                self.retrieve_field(url).addCallback(render_feed)
                for url in self._feed_urls
            ]
        }
Пример #11
0
class FeedAggregation(object):
    _retrieve = attr.ib()
    _urls = attr.ib()
    _app = Klein()
    _planting = Plating(
        tags=t.html(
            t.head(t.title('Feed Aggregator 2.0')),
            t.body(slot(Plating.CONTENT))
        )
    )

    def resource(self):
        return self._app.resource()

    @_planting.routed(
        _app.route('/'),
        t.div(render='feeds:list')(slot('item')),
    )
    def root(self, request):
        def convert(feed):
            return feed.as_json() if request.args.get(b'json') else feed.as_html()
        return {'feeds': [self._retrieve(url).addCallback(convert) for url in self._urls]}
Пример #12
0
class FeedAggregation(object):
    _retrieve = attr.ib()
    _urls = attr.ib()
    _app = Klein()
    _plating = Plating(tags=t.html(t.head(t.title("Feed Aggregator 2.0")),
                                   t.body(slot(Plating.CONTENT))))

    def resource(self):
        return self._app.resource()

    @_plating.routed(
        _app.route("/"),
        t.div(render="feeds:list")(slot("item")),
    )
    def root(self, request):
        def convert(feed):
            return feed.asJSON() if request.args.get(
                b"json") else feed.asHTML()

        return {
            "feeds":
            [self._retrieve(url).addCallback(convert) for url in self._urls]
        }
Пример #13
0
class SlowIncrementWebService(object):
    application = Klein()
    common_page = Plating(tags=tags.html(
        tags.head(
            tags.title(slot('title')),
            tags.style('#amount { font-weight: bold; }'
                       '#message { font-style: italic; }')),
        tags.body(tags.div(slot(Plating.CONTENT)))))

    def __init__(self, reactor):
        self._reactor = reactor

    @common_page.routed(application.route('/<int:amount>'),
                        tags.div(
                            tags.span('Hello! Your new amount is: ',
                                      id='message'),
                            tags.span(slot('new_amount'), id='amount'),
                        ))
    def slow_increment(self, request, amount):
        slots = {
            'title': 'Slow Increment',
            'new_amount': amount + 1,
        }
        return task.deferLater(self._reactor, 1.0, lambda: slots)
Пример #14
0
from hashlib import sha256
from struct import unpack

def random_from_string(string):
    return Random(
        unpack("!I", sha256(string.encode("utf-8")).digest()[:4])[0]
    )

from twisted.web.template import tags, slot
from klein import Klein, Plating
app = Klein()

style = Plating(
    tags=tags.html(
        tags.head(tags.title(slot("title"))),
        tags.body(tags.h1(slot("title"), Class="title"),
                  tags.div(slot(Plating.CONTENT)))
    ),
    defaults={"title": "Places & Foods"}
)

@style.routed(
    app.route("/"),
    tags.div(
        tags.h2("Sample Places:"),
        tags.ul([tags.li(tags.a(href=["/places/", place])(place))
                 for place in ["new york", "san francisco", "shanghai"]]),
        tags.h2("Sample Foods:"),
        tags.ul([tags.li(tags.a(href=["/foods/", food])(food))
                 for food in ["hamburgers", "cheeseburgers", "hot dogs"]]),
    ))
def root(request):
Пример #15
0
from twisted.web.template import slot, tags

from .test_resource import _render, requestMock
from .. import Klein, Plating
from .._plating import ATOM_TYPES, PlatedElement, resolveDeferredObjects


page = Plating(
    defaults={
        "title": "default title unchanged",
        Plating.CONTENT: "NEVER MIND THE CONTENT",
    },
    tags=tags.html(
        tags.head(tags.title(slot("title"))),
        tags.body(
            tags.h1(slot("title")),
            tags.div(slot(Plating.CONTENT), Class="content"),
        ),
    ),
)

element = Plating(
    defaults={
        "a": "NO VALUE FOR A",
        "b": "NO VALUE FOR B",
    },
    tags=tags.div(
        tags.span("a: ", slot("a")),
        tags.span("b: ", slot("b")),
    ),
)
Пример #16
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from klein import run, route
from twisted.web.template import tags, slot
from klein import Klein, Plating

from input_handler import handle_input

app = Klein()

myStyle = Plating(
    tags=tags.html(
        tags.head(tags.title(slot("pageTitle"))),
        tags.body(tags.h1(slot("pageTitle"), Class="titleHeading"),
                  tags.div(slot(Plating.CONTENT)))
    )
)

@myStyle.routed(
    app.route("/input/"),
    tags.div())
def input(request):
	return {"r":['Hello, world!']}



if __name__ == '__main__':
	app.run("localhost", 8080)
    
Пример #17
0
from hashlib import sha256
from struct import unpack

def random_from_string(string):
    return Random(
        unpack("!I", sha256(string.encode("utf-8")).digest()[:4])[0]
    )

from twisted.web.template import tags, slot
from klein import Klein, Plating
app = Klein()

myStyle = Plating(
    tags=tags.html(
        tags.head(tags.title(slot("pageTitle"))),
        tags.body(tags.h1(slot("pageTitle"), Class="titleHeading"),
                  tags.div(slot(Plating.CONTENT)))
    ),
    defaults={"pageTitle": "Places & Foods"}
)

@myStyle.routed(
    app.route("/"),
    tags.div(
        tags.h2("Sample Places:"),
        tags.ul([tags.li(tags.a(href=["/places/", place])(place))
                 for place in ["new york", "san francisco", "shanghai"]]),
        tags.h2("Sample Foods:"),
        tags.ul([tags.li(tags.a(href=["/foods/", food])(food))
                 for food in ["hamburgers", "cheeseburgers", "hot dogs"]]),
    ))
def root(request):
Пример #18
0
from klein.storage.memory import MemorySessionStore

app = Klein()

sessions = MemorySessionStore()

requirer = Requirer()


@requirer.prerequisite([ISession])
def procurer(request):
    return SessionProcurer(sessions).procureSession(request)


style = Plating(tags=tags.html(tags.head(tags.title("yay")),
                               tags.body(tags.div(slot(Plating.CONTENT)))))


@requirer.require(
    style.routed(
        app.route("/", methods=["POST"]),
        tags.h1("u did it: ", slot("an-form-arg")),
    ),
    foo=Field.number(minimum=3, maximum=10),
    bar=Field.text(),
)
def postHandler(foo, bar):
    return {"an-form-arg": foo}


@requirer.require(
Пример #19
0
from twisted.web.error import FlattenerError, MissingRenderMethod
from twisted.web.template import slot, tags

from .test_resource import _render, requestMock
from .. import Klein, Plating
from .._plating import ATOM_TYPES, PlatedElement, resolveDeferredObjects

page = Plating(
    defaults={
        "title": "default title unchanged",
        Plating.CONTENT: "NEVER MIND THE CONTENT",
    },
    tags=tags.html(
        tags.head(tags.title(slot("title"))),
        tags.body(
            tags.h1(slot("title")),
            tags.div(slot(Plating.CONTENT), Class="content"),
        ),
    ),
)

element = Plating(
    defaults={
        "a": "NO VALUE FOR A",
        "b": "NO VALUE FOR B",
    },
    tags=tags.div(
        tags.span("a: ", slot("a")),
        tags.span("b: ", slot("b")),
    ),
)
def make_html(components, instances):
    table = tags.table(class_='main')
    heading_row = tags.tr()
    for heading in 'component', 'tip revno', 'unreleased revisions', 'latest release':
        heading_row(tags.th(heading))
    for instance_name in sorted(instances):
        heading_row(tags.th(instance_name, class_="instance-name"))
    table(tags.thead(heading_row))
    tbody = tags.tbody()
    for name, component in sorted(components.items()):
        row = tags.tr(class_="component")
        revs_between_ids = {}
        extra_rows = []

        def td(*args, **kwargs):
            row(tags.td(*args, **kwargs))

        td(name)
        td(str(component.tip_revno), class_='version')
        unreleased_count = len(component.unreleased_revisions)
        if unreleased_count:
            id_ = get_id()
            td(tags.a(str(unreleased_count), href='#', class_='highlight'),
               class_='version clickable',
               id=id_)
            sub_name = 'revs between %s (r%s) and tip (r%s)' % (
                component.last_release, component.released_revno,
                component.tip_revno)
            extra_rows.append(
                tags.tr(tags.td(format_revlist(component.unreleased_revisions,
                                               name=sub_name),
                                colspan=str(4 + len(instances))),
                        class_='hidden',
                        id="show-" + id_))
        elif not component.last_release:
            td(u'\N{EM DASH}', class_='version')
        else:
            td(str(unreleased_count), class_='version')
        if component.last_release:
            td(component.last_release, class_='version')
        else:
            td(u'???', class_='version')
        for instance_name, instance in sorted(instances.items()):
            ver, location = instance.get(name, (None, None))
            if ver is None:
                td(u'\N{EM DASH}', class_='version')
            elif ver == component.last_release:
                td(ver, class_='version')
            elif ver in component.release2revno:
                revno_low = component.release2revno[ver]
                sub_name = 'revs between %s (r%s) and %s (r%s)' % (
                    ver, revno_low, component.last_release,
                    component.released_revno)
                revlist = []
                for rev, revno in component.mainline_revs:
                    if revno_low < revno < component.released_revno:
                        revlist.append((rev, revno))
                if revlist:
                    id_ = get_id()
                    revs_between_ids[revno_low] = id_
                    extra_rows.append(
                        tags.tr(tags.td(format_revlist(revlist, name=sub_name),
                                        colspan=str(4 + len(instances))),
                                class_='hidden branch-diff',
                                id="show-" + id_))
                    td(tags.a(ver, href='#', class_='highlight'),
                       class_='version clickable',
                       id=id_)
                else:
                    td(tags.span(ver, class_='highlight'), class_='version')
            elif location:
                try:
                    branch = bzrlib.branch.Branch.open(location)
                except bzrlib.errors.NoSuchBranch:
                    td(tags.span(ver, class_='highlight'), class_='version')
                else:
                    branch.lock_read()
                    try:
                        # This utterly half-assed version of bzr missing
                        # doesn't take merges into account!
                        revno, revid = branch.last_revision_info()
                        ver = ver.split('dev')[0] + 'dev' + str(revno)
                        mainline_revids = dict(
                            (rev.revision_id, revno)
                            for rev, revno in component.mainline_revs)
                        in_branch_revs = []
                        while revid not in mainline_revids:
                            rev = branch.repository.get_revision(revid)
                            if rev.message != 'post release bump':
                                in_branch_revs.append((rev, revno))
                            revno -= 1
                            if not rev.parent_ids:
                                break
                            revid = rev.parent_ids[0]
                        tables = []
                        if in_branch_revs:
                            tables.append(
                                format_revlist(
                                    in_branch_revs,
                                    'in branch (with nick %s) but not tip' %
                                    branch.nick))
                        in_trunk_revs = []
                        lca_revno = revno
                        for rev, revno in component.mainline_revs:
                            if revno > lca_revno:
                                in_trunk_revs.append((rev, revno))
                        if in_trunk_revs:
                            tables.append(
                                format_revlist(in_trunk_revs,
                                               'in tip but not branch'))
                        if tables:
                            id_ = get_id()
                            td(tags.a(ver, href='#', class_='highlight'),
                               class_='version clickable',
                               id=id_)
                            extra_rows.append(
                                tags.tr(tags.td(tables,
                                                colspan=str(4 +
                                                            len(instances))),
                                        class_='hidden branch-diff',
                                        id="show-" + id_))
                        else:
                            if branch.last_revision() == component.tip_revno:
                                td(ver, class_='highlight version')
                            else:
                                td(ver, class_='version')
                    finally:
                        branch.unlock()
            else:
                td(tags.span(ver, class_='highlight'), class_='version')
        tbody(row, *extra_rows)
    table(tbody)
    html = tags.html(
        tags.head(
            tags.title("Deployment report"),
            tags.script(
                src=
                'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
                type='text/javascript'),
            tags.script(
                src=
                'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
                type='text/javascript'),
            tags.script(CDATA(js), type='text/javascript'),
            tags.style(CDATA(css), type="text/css"),
        ),
        tags.body(
            tags.h1("Deployment report"),
            table,
        ),
    )
    html(xmlns="http://www.w3.org/1999/xhtml")
    return DOCTYPE + flatten(html)
Пример #21
0
from twisted.web.template import slot, tags

from .test_resource import _render, requestMock
from .. import Klein, Plating
from .._plating import ATOM_TYPES, PlatedElement, resolveDeferredObjects

page = Plating(
    defaults={
        "title": "default title unchanged",
        Plating.CONTENT: "NEVER MIND THE CONTENT",
    },
    tags=tags.html(
        tags.head(tags.title(slot("title"))),
        tags.body(
            tags.h1(slot("title")),
            tags.div(slot(Plating.CONTENT), Class="content"),
            tags.div(id="rendermethod", render="registeredRenderMethod"),
        ),
    ),
)

element = Plating(
    defaults={
        "a": "NO VALUE FOR A",
        "b": "NO VALUE FOR B",
    },
    tags=tags.div(
        tags.span("a: ", slot("a")),
        tags.span("b: ", slot("b")),
    ),
)
def make_html(components, instances):
    table = tags.table(class_='main')
    heading_row = tags.tr()
    for heading in  'component', 'tip revno', 'unreleased revisions', 'latest release':
        heading_row(tags.th(heading))
    for instance_name in sorted(instances):
        heading_row(tags.th(instance_name, class_="instance-name"))
    table(tags.thead(heading_row))
    tbody = tags.tbody()
    for name, component in sorted(components.items()):
        row = tags.tr(class_="component")
        revs_between_ids = {}
        extra_rows = []
        def td(*args, **kwargs):
            row(tags.td(*args, **kwargs))
        td(name)
        td(str(component.tip_revno), class_='version')
        unreleased_count = len(component.unreleased_revisions)
        if unreleased_count:
            id_ = get_id()
            td(
                tags.a(str(unreleased_count), href='#', class_='highlight'),
                class_='version clickable', id=id_)
            sub_name = 'revs between %s (r%s) and tip (r%s)' % (
                component.last_release, component.released_revno,
                component.tip_revno)
            extra_rows.append(
                tags.tr(
                    tags.td(
                        format_revlist(component.unreleased_revisions, name=sub_name),
                        colspan=str(4 + len(instances))),
                    class_='hidden',
                    id="show-" + id_))
        elif not component.last_release:
            td(u'\N{EM DASH}', class_='version')
        else:
            td(str(unreleased_count), class_='version')
        if component.last_release:
            td(component.last_release, class_='version')
        else:
            td(u'???', class_='version')
        for instance_name, instance in sorted(instances.items()):
            ver, location = instance.get(name, (None, None))
            if ver is None:
                td(u'\N{EM DASH}', class_='version')
            elif ver == component.last_release:
                td(ver, class_='version')
            elif ver in component.release2revno:
                revno_low = component.release2revno[ver]
                sub_name = 'revs between %s (r%s) and %s (r%s)' % (
                    ver, revno_low,
                    component.last_release, component.released_revno)
                revlist = []
                for rev, revno in component.mainline_revs:
                    if revno_low < revno < component.released_revno:
                        revlist.append((rev, revno))
                if revlist:
                    id_ = get_id()
                    revs_between_ids[revno_low] = id_
                    extra_rows.append(
                        tags.tr(
                            tags.td(
                                format_revlist(revlist, name=sub_name),
                                colspan=str(4 + len(instances))),
                            class_='hidden branch-diff',
                            id="show-" + id_))
                    td(
                        tags.a(ver, href='#', class_='highlight'),
                        class_='version clickable', id=id_)
                else:
                    td(tags.span(ver, class_='highlight'), class_='version')
            elif location:
                try:
                    branch = bzrlib.branch.Branch.open(location)
                except bzrlib.errors.NoSuchBranch:
                    td(tags.span(ver, class_='highlight'), class_='version')
                else:
                    branch.lock_read()
                    try:
                        # This utterly half-assed version of bzr missing
                        # doesn't take merges into account!
                        revno, revid = branch.last_revision_info()
                        ver = ver.split('dev')[0] + 'dev' + str(revno)
                        mainline_revids = dict(
                            (rev.revision_id, revno)
                            for rev, revno in component.mainline_revs)
                        in_branch_revs = []
                        while revid not in mainline_revids:
                            rev = branch.repository.get_revision(revid)
                            if rev.message != 'post release bump':
                                in_branch_revs.append((rev, revno))
                            revno -= 1
                            if not rev.parent_ids:
                                break
                            revid = rev.parent_ids[0]
                        tables = []
                        if in_branch_revs:
                            tables.append(
                                format_revlist(
                                    in_branch_revs,
                                    'in branch (with nick %s) but not tip' % branch.nick))
                        in_trunk_revs = []
                        lca_revno = revno
                        for rev, revno in component.mainline_revs:
                            if revno > lca_revno:
                                in_trunk_revs.append((rev, revno))
                        if in_trunk_revs:
                            tables.append(
                                format_revlist(
                                    in_trunk_revs,
                                    'in tip but not branch'))
                        if tables:
                            id_ = get_id()
                            td(
                                tags.a(ver, href='#', class_='highlight'),
                                class_='version clickable', id=id_)
                            extra_rows.append(
                                tags.tr(
                                    tags.td(
                                        tables,
                                        colspan=str(4 + len(instances))),
                                    class_='hidden branch-diff',
                                    id="show-" + id_))
                        else:
                            if branch.last_revision() == component.tip_revno:
                                td(ver, class_='highlight version')
                            else:
                                td(ver, class_='version')
                    finally:
                        branch.unlock()
            else:
                td(tags.span(ver, class_='highlight'), class_='version')
        tbody(row, *extra_rows)
    table(tbody)
    html = tags.html(
        tags.head(
            tags.title("Deployment report"),
            tags.script(
                src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
                type='text/javascript'),
            tags.script(
                src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
                type='text/javascript'),
            tags.script(CDATA(js), type='text/javascript'),
            tags.style(CDATA(css), type="text/css"),
            ),
        tags.body(
            tags.h1("Deployment report"),
            table,
            ),
        )
    html(xmlns="http://www.w3.org/1999/xhtml")
    return DOCTYPE + flatten(html)