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)
def generateTabsAndContent(results): """ results is a dictionary whose keys are normalized ASCII chars and whose values are the original (possible unicode) chars that map to the ASCII ones. """ tabs = [] contents = [] for asciiLetter in sorted(results.keys()): if not asciiLetter: continue for letter in sorted(results[asciiLetter]): tab = tags.li( tags.a( letter.upper(), href="#l%s" % letter, **{"data-toggle": "tab"}) ) tabs.append(tab) content = tags.div( tags.p("holding content"), class_="tab-pane", id="l%s" % letter) contents.append(content) return tags.div( tags.ul(tabs, class_="nav nav-tabs"), tags.div(contents, class_="tab-content"), class_="tabbable tabs-left")
def test_template_numbers(self): """ Data returned from a plated method may include numeric types (integers, floats, and possibly longs), which although they are not normally serializable by twisted.web.template, will be converted by plating into their decimal representation. """ @page.routed( self.app.route("/"), tags.div( tags.span(slot("anInteger")), tags.i(slot("anFloat")), tags.b(slot("anLong")), ), ) def plateMe(result): return {"anInteger": 7, "anFloat": 3.2, "anLong": 0x10000000000000001} request, written = self.get(b"/") self.assertIn(b"<span>7</span>", written) self.assertIn(b"<i>3.2</i>", written) self.assertIn(b"<b>18446744073709551617</b>", written)
def functionExtras(self, data): imeth = self.interfaceMeth(data.name) r = [] if imeth: r.append(tags.div(class_="interfaceinfo")('from ', taglink(imeth, imeth.parent.fullName()))) r.extend(super(ZopeInterfaceClassPage, self).functionExtras(data)) return r
def functionExtras(self, data): r = [] for b in self.ob.allbases(include_self=False): if data.name not in b.contents: continue overridden = b.contents[data.name] r.append(tags.div(class_="interfaceinfo")("overrides ", taglink(overridden))) break ocs = sorted(overriding_subclasses(self.ob, data.name), key=lambda o: o.fullName().lower()) if ocs: self.overridenInCount += 1 idbase = "overridenIn" + str(self.overridenInCount) l = assembleList(self.ob.system, "overridden in ", [o.fullName() for o in ocs], idbase) if l is not None: r.append(tags.div(class_="interfaceinfo")(l)) return r
def test_sourceFragmentElement(self): """ L{_SourceFragmentElement} renders source lines at and around the line number indicated by a frame object. """ element = _SourceFragmentElement( TagLoader(tags.div( tags.span(render="lineNumber"), tags.span(render="sourceLine"), render="sourceLines")), self.frame) source = [ u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}message = ' u'"This is a problem"', u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}raise Exception(message)', u'# Figure out the line number from which the exception will be ' u'raised.', ] d = flattenString(None, element) d.addCallback( self.assertEqual, ''.join([ '<div class="snippet%sLine"><span>%d</span><span>%s</span>' '</div>' % ( ["", "Highlight"][lineNumber == 1], self.base + lineNumber, (u" \N{NO-BREAK SPACE}" * 4 + sourceLine).encode( 'utf-8')) for (lineNumber, sourceLine) in enumerate(source)])) return d
def test_widget_json(self): """ When L{Plating.widgeted} is applied as a decorator, and the result is serialized to JSON, it appears the same as the returned value despite the HTML-friendly wrapping described above. """ @page.routed(self.app.route("/"), tags.div(tags.div(slot("widget")), tags.div(slot("instance-widget")))) def rsrc(request): return {"widget": enwidget.widget(a=3, b=4), "instance-widget": InstanceWidget().enwidget.widget(5, 6)} request, written = self.get(b"/?json=1") self.assertEqual(json.loads(written.decode('utf-8')), {"widget": {"a": 3, "b": 4}, "instance-widget": {"a": 5, "b": 6}, "title": "default title unchanged"})
def test_widget_html(self): """ When L{Plating.widgeted} is applied as a decorator, it gives the decorated function a C{widget} attribute which is a version of the function with a modified return type that turns it into a renderable HTML sub-element that may fill a slot. """ @page.routed(self.app.route("/"), tags.div(tags.div(slot("widget")), tags.div(slot("instance-widget")))) def rsrc(request): return {"widget": enwidget.widget(a=3, b=4), "instance-widget": InstanceWidget().enwidget.widget(5, 6)} request, written = self.get(b"/") self.assertIn(b"<span>a: 3</span>", written) self.assertIn(b"<span>b: 4</span>", written) self.assertIn(b"<span>a: 5</span>", written) self.assertIn(b"<span>b: 6</span>", written)
def test_failureElementTraceback(self): """ The I{traceback} renderer of L{FailureElement} renders the failure's stack frames using L{_StackElement}. """ element = FailureElement(self.failure) renderer = element.lookupRenderMethod("traceback") tag = tags.div() result = renderer(None, tag) self.assertIsInstance(result, _StackElement) self.assertIdentical(result.stackFrames, self.failure.frames) self.assertEqual([tag], result.loader.load())
def main(self, request, tag): retval = [] for automaton in factory.automatons: title = tags.h2(automaton.name) stats = [] # Discover tracked information. if hasattr(automaton, "tracked"): t = automaton.tracked if isinstance(t, dict): l = sum(len(i) for i in t.values()) else: l = len(t) stats.append(tags.li("Currently tracking %d blocks" % l)) if hasattr(automaton, "step"): stats.append(tags.li("Currently processing every %f seconds" % automaton.step)) retval.append(tags.div(title, tags.ul(stats))) return tags.div(*retval)
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 test_frameElementSource(self): """ The I{source} renderer of L{_FrameElement} renders the source code near the source filename/line number associated with the frame object used to initialize the L{_FrameElement}. """ element = _FrameElement(None, self.frame) renderer = element.lookupRenderMethod("source") tag = tags.div() result = renderer(None, tag) self.assertIsInstance(result, _SourceFragmentElement) self.assertIdentical(result.frame, self.frame) self.assertEqual([tag], result.loader.load())
def body(self, req): status = self.getStatus(req) authz = self.getAuthz(req) builders = req.args.get( "builder", status.getBuilderNames(categories=self.categories)) branches = [b for b in req.args.get("branch", []) if b] if not branches: branches = ["master"] if branches and "master" not in branches: defaultCount = "1" else: defaultCount = "10" num_builds = int(req.args.get("num_builds", [defaultCount])[0]) tag = tags.div() tag(tags.script(src="hlbb.js")) tag(tags.h2(style="float:left; margin-top:0") ("Latest builds: ", ", ".join(branches))) form = tags.form(method="get", action="", style="float:right", onsubmit="return checkBranch(branch.value)") form(tags.input(type="test", name="branch", placeholder=branches[0], size="40")) form(tags.input(type="submit", value="View")) if (yield authz.actionAllowed('forceAllBuilds', req)): # XXX: Unsafe interpolation form(tags.button( type="button", onclick="forceBranch(branch.value || %r, %r)" % (branches[0], self.categories,) )("Force")) tag(form) table = tags.table(style="clear:both") tag(table) for bn in filter(lambda bn: bn not in self.failing_builders, builders): table(self.builder_row(bn, req, branches, num_builds)) table(tags.tr()(tags.td(colspan="100")( tags.h3(style="float:left; margin-top:0") ("Expected failures: ")))) for bn in filter(lambda bn: bn in self.failing_builders, builders): table(self.builder_row(bn, req, branches, num_builds)) defer.returnValue((yield flattenString(req, tag)))
def test_sourceLineElement(self): """ L{_SourceLineElement} renders a source line and line number. """ element = _SourceLineElement( TagLoader(tags.div( tags.span(render="lineNumber"), tags.span(render="sourceLine"))), 50, " print 'hello'") d = flattenString(None, element) expected = ( u"<div><span>50</span><span>" u" \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}print 'hello'</span></div>") d.addCallback( self.assertEqual, expected.encode('utf-8')) return d
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)
def test_stackElement(self): """ The I{frames} renderer of L{_StackElement} renders each stack frame in the list of frames used to initialize the L{_StackElement}. """ element = _StackElement(None, self.failure.frames[:2]) renderer = element.lookupRenderMethod("frames") tag = tags.div() result = renderer(None, tag) self.assertIsInstance(result, list) self.assertIsInstance(result[0], _FrameElement) self.assertIdentical(result[0].frame, self.failure.frames[0]) self.assertIsInstance(result[1], _FrameElement) self.assertIdentical(result[1].frame, self.failure.frames[1]) # They must not share the same tag object. self.assertNotEqual(result[0].loader.load(), result[1].loader.load()) self.assertEqual(2, len(result))
def stanForOb(self, ob, summary=False): current_docstring = self.currentDocstringForObject(ob) if summary: return epydoc2stan.doc2stan( ob.doctarget, summary=True, docstring=current_docstring)[0] r = [tags.div(epydoc2stan.doc2stan(ob.doctarget, docstring=current_docstring)[0]), tags.a(href="edit?ob="+ob.fullName())("Edit"), " "] if ob.doctarget in self.editsbyob: r.append(tags.a(href="history?ob="+ob.fullName())( "View docstring history (", str(len(self.editsbyob[ob.doctarget])), " versions)")) else: r.append(tags.span(class_='undocumented')("No edits yet.")) return r
def entry_rendered(entry): if entry.system_entry: attrs_entry = attrs_entry_system else: attrs_entry = attrs_entry_user return tags.div( tags.span( str(entry.created), u", ", entry.author, **attrs_timestamp ), ":", tags.br(), tags.span( entry.text, **attrs_entry_text ), **attrs_entry )
def body(self, req): status = self.getStatus(req) authz = self.getAuthz(req) builders = req.args.get( "builder", status.getBuilderNames(categories=self.categories)) branches = [b for b in req.args.get("branch", []) if b] if not branches: branches = ["trunk"] if branches and "trunk" not in branches: defaultCount = "1" else: defaultCount = "10" num_builds = int(req.args.get("num_builds", [defaultCount])[0]) tag = tags.div() tag(tags.script(src="txbuildbot.js")) tag( tags.h2(style="float:left; margin-top:0")("Latest builds: ", ", ".join(branches))) form = tags.form(method="get", action="", style="float:right", onsubmit="return checkBranch(branch.value)") form( tags.input(type="test", name="branch", placeholder=branches[0], size="40")) form(tags.input(type="submit", value="View")) if (yield authz.actionAllowed('forceAllBuilds', req)): # XXX: Unsafe interpolation form( tags.button(type="button", onclick="forceBranch(branch.value || %r, %r)" % ( branches[0], self.categories, ))("Force")) tag(form) table = tags.table(style="clear:both") tag(table) for bn in builders: builder = status.getBuilder(bn) state = builder.getState()[0] if state == 'building': state = 'idle' row = tags.tr() table(row) builderLink = path_to_builder(req, builder) row( tags.td(class_="box %s" % (state, ))( tags.a(href=builderLink)(bn))) builds = sorted([ build for build in builder.getCurrentBuilds() if build.getSourceStamps()[0].branch in map_branches(branches) ], key=lambda build: build.getNumber(), reverse=True) builds.extend( builder.generateFinishedBuilds(map_branches(branches), num_builds=num_builds)) if builds: for b in builds: url = path_to_build(req, b) try: label = b.getProperty("got_revision") except KeyError: label = None # Label should never be "None", but sometimes # buildbot has disgusting bugs. if not label or label == "None" or len(str(label)) > 20: label = "#%d" % b.getNumber() if b.isFinished(): text = b.getText() else: when = b.getETA() if when: text = [ "%s" % (formatInterval(when), ), "%s" % (time.strftime( "%H:%M:%S", time.localtime(time.time() + when)), ) ] else: text = [] row( tags.td( align="center", bgcolor=_backgroundColors[b.getResults()], class_=("LastBuild box ", build_get_class(b)))([ (element, tags.br) for element in [tags.a(href=url)(label)] + text ])) else: row(tags.td(class_="LastBuild box")("no build")) defer.returnValue((yield flattenString(req, tag)))
def r3(self, req, tag): return tag.fillSlots(meep=(u"slotvalue", u"42", b"bar", tags.div(u"meep", attr=u"value")))
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)
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 r2(self, req, tag): return tags.div(u"foo", attr=u"value")
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):
def doc2stan(obj, summary=False, docstring=None): """Generate an HTML representation of a docstring""" if getattr(obj, 'parsed_docstring', None) is not None: r = html2stan(obj.parsed_docstring.to_html(_EpydocLinker(obj))) if getattr(obj, 'parsed_type', None) is not None: r = [r, ' (type: ', html2stan(obj.parsed_type.to_html(_EpydocLinker(obj))), ')'] return r, [] origobj = obj if isinstance(obj, model.Package): obj = obj.contents['__init__'] if docstring is None: doc = None for source in obj.docsources(): if source.docstring is not None: doc = source.docstring break else: source = obj doc = docstring if doc is None or not doc.strip(): text = "Undocumented" subdocstrings = {} subcounts = {} for subob in origobj.contents.itervalues(): k = subob.kind.lower() subcounts[k] = subcounts.get(k, 0) + 1 if subob.docstring is not None: subdocstrings[k] = subdocstrings.get(k, 0) + 1 if isinstance(origobj, model.Package): subcounts["module"] -= 1 if subdocstrings: plurals = {'class':'classes'} text = "No %s docstring"%origobj.kind.lower() if summary: u = [] for k in sorted(subcounts): u.append("%s/%s %s"%(subdocstrings.get(k, 0), subcounts[k], plurals.get(k, k+'s'))) text += '; ' + ', '.join(u) + " documented" if summary: return tags.span(class_="undocumented")(text), [] else: return tags.div(class_="undocumented")(text), [] if summary: # Use up to three first non-empty lines of doc string as summary. lines = itertools.dropwhile(lambda line: not line.strip(), doc.split('\n')) lines = itertools.takewhile(lambda line: line.strip(), lines) lines = [ line.strip() for line in lines ] if len(lines) > 3: return tags.span(class_="undocumented")('No summary'), [] else: doc = ' '.join(lines) parse_docstring, e = get_parser(obj.system.options.docformat) if not parse_docstring: msg = 'Error trying to import %r parser:\n\n %s: %s\n\nUsing plain text formatting only.'%( obj.system.options.docformat, e.__class__.__name__, e) obj.system.msg('epydoc2stan', msg, thresh=-1, once=True) return boringDocstring(doc, summary), [] errs = [] def crappit(): pass crappit.__doc__ = doc doc = inspect.getdoc(crappit) try: pdoc = parse_docstring(doc, errs) except Exception, e: errs = [e.__class__.__name__ +': ' + str(e)]
else: crap = '' if isinstance(crap, unicode): crap = crap.encode('utf-8') if summary: if not crap: return (), [] stan = html2stan(crap) if len(stan) == 1 and isinstance(stan[0], Tag) and stan[0].tagName == 'p': stan = stan[0].children s = tags.span(stan) else: if not crap and not fields: return (), [] stan = html2stan(crap) s = tags.div(stan) fh = FieldHandler(obj) for field in fields: fh.handle(Field(field, obj)) fh.resolve_types() s(fh.format()) return s, [] field_name_to_human_name = { 'ivar': 'Instance Variable', 'cvar': 'Class Variable', 'var': 'Variable', }
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 body(self, req): status = self.getStatus(req) authz = self.getAuthz(req) builders = req.args.get("builder", status.getBuilderNames(categories=self.categories)) branches = [b for b in req.args.get("branch", []) if b] if not branches: branches = ["trunk"] if branches and "trunk" not in branches: defaultCount = "1" else: defaultCount = "10" num_builds = int(req.args.get("num_builds", [defaultCount])[0]) tag = tags.div() tag(tags.script(src="txbuildbot.js")) tag(tags.h2(style="float:left; margin-top:0")("Latest builds: ", ", ".join(branches))) form = tags.form(method="get", action="", style="float:right", onsubmit="return checkBranch(branch.value)") form(tags.input(type="test", name="branch", placeholder=branches[0], size="40")) form(tags.input(type="submit", value="View")) if (yield authz.actionAllowed('forceAllBuilds', req)): # XXX: Unsafe interpolation form(tags.button(type="button", onclick="forceBranch(branch.value || %r, %r)" % (branches[0], self.categories,) )("Force")) tag(form) table = tags.table(style="clear:both") tag(table) for bn in builders: builder = status.getBuilder(bn) state = builder.getState()[0] if state == 'building': state = 'idle' row = tags.tr() table(row) builderLink = path_to_builder(req, builder) row(tags.td(class_="box %s" % (state,))(tags.a(href=builderLink)(bn))) builds = sorted([ build for build in builder.getCurrentBuilds() if build.getSourceStamps()[0].branch in map_branches(branches) ], key=lambda build: build.getNumber(), reverse=True) builds.extend(builder.generateFinishedBuilds(map_branches(branches), num_builds=num_builds)) if builds: for b in builds: url = path_to_build(req, b) try: label = b.getProperty("got_revision") except KeyError: label = None # Label should never be "None", but sometimes # buildbot has disgusting bugs. if not label or label == "None" or len(str(label)) > 20: label = "#%d" % b.getNumber() if b.isFinished(): text = b.getText() else: when = b.getETA() if when: text = [ "%s" % (formatInterval(when),), "%s" % (time.strftime("%H:%M:%S", time.localtime(time.time() + when)),) ] else: text = [] row(tags.td( align="center", bgcolor=_backgroundColors[b.getResults()], class_=("LastBuild box ", build_get_class(b)))([ (element, tags.br) for element in [tags.a(href=url)(label)] + text]) ) else: row(tags.td(class_="LastBuild box")("no build")) defer.returnValue((yield flattenString(req, tag)))
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")), ), )