def error_page(request, resrc, value, tb=None): result = "Request: %s<br />\nResource: %s<br />\nValue: %s" % ( html.PRE(reflect.safe_repr(request)), html.PRE(reflect.safe_repr(resrc)), html.PRE(reflect.safe_repr(value)), ) if tb: result += '\n%s' % html.PRE(reflect.safe_str(tb)) return result
def render(self, request): """Render me to a web client. Load my file, execute it in a special namespace (with 'request' and '__file__' global vars) and finish the request. Output to the web-page will NOT be handled with print - standard output goes to the log - but with request.write. """ request.setHeader("x-powered-by","Twisted/14") namespace = {'request': request, '__file__': self.filename, 'registry': self.registry} try: f = open(self.filename,'r') buf = f.read() f.close() mystr = "__tmp_variable = %s" % buf dc = DictConfig(excstr=mystr) d = dc.__tmp_variable return jsonEncode(d) # execfile(self.filename, namespace, namespace) except IOError as e: if e.errno == 2: #file not found request.setResponseCode(http.NOT_FOUND) request.write(resource.NoResource("File not found.").render(request)) except: io = StringIO.StringIO() traceback.print_exc(file=io) request.write(html.PRE(io.getvalue()))
def render(self, request): """ Render me to a web client. Load my file, execute it in a special namespace (with 'request' and '__file__' global vars) and finish the request. Output to the web-page will NOT be handled with print - standard output goes to the log - but with request.write. """ request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version)) namespace = { 'request': request, '__file__': _coerceToFilesystemEncoding("", self.filename), 'registry': self.registry } try: execfile(self.filename, namespace, namespace) except IOError as e: if e.errno == 2: #file not found request.setResponseCode(http.NOT_FOUND) request.write( resource.NoResource("File not found.").render(request)) except: io = NativeStringIO() traceback.print_exc(file=io) output = html.PRE(io.getvalue()) if _PY3: output = output.encode("utf8") request.write(output) request.finish() return server.NOT_DONE_YET
def asHTML(self): links = [] for file in self.files: link = filter(lambda s: s.find(file) != -1, self.links) if len(link) == 1: # could get confused links.append('<a href="%s"><b>%s</b></a>' % (link[0], file)) else: links.append('<b>%s</b>' % file) revision = "" if self.revision: revision = "Revision: <b>%s</b><br />\n" % self.revision branch = "" if self.branch: branch = "Branch: <b>%s</b><br />\n" % self.branch kwargs = { 'who': html.escape(self.who), 'at': self.getTime(), 'files': html.UL(links) + '\n', 'revision': revision, 'branch': branch, 'comments': html.PRE(self.comments) } return html_tmpl % kwargs
def configWidget(self, request): # displaying the widget path = request.postpath if path: obj = self.app for elem in path: if elem: # '' doesn't count obj = obj.getStaticEntity(elem) if obj is None: request.setResponseCode(http.MOVED_PERMANENTLY) request.setHeader('location', request.prePathURL()) return ['Redirecting...'] else: obj = self.app ret = [] linkfrom = string.join(['config'] + request.postpath, '/') + '/' if isinstance(obj, coil.Configurable) and obj.configTypes: ret.extend( widgets.TitleBox("Configuration", ConfigForm(self, obj, linkfrom)).display(request)) if isinstance(obj, roots.Homogenous ): # and isinstance(obj.entityType, coil.Configurable): ret.extend( widgets.TitleBox("Listing", CollectionForm(self, obj, linkfrom)).display(request)) ret.append(html.PRE(str(obj))) return ret
def test_deprecation(self): """ Calls to L{twisted.web.html} members emit a deprecation warning. """ def assertDeprecationWarningOf(method): """ Check that a deprecation warning is present. """ warningsShown = self.flushWarnings([self.test_deprecation]) self.assertEqual(len(warningsShown), 1) self.assertIdentical(warningsShown[0]['category'], DeprecationWarning) self.assertEqual( warningsShown[0]['message'], 'twisted.web.html.%s was deprecated in Twisted 15.3.0; ' 'please use twisted.web.template instead' % (method, ), ) html.PRE('') assertDeprecationWarningOf('PRE') html.UL([]) assertDeprecationWarningOf('UL') html.linkList([]) assertDeprecationWarningOf('linkList') html.output(lambda: None) assertDeprecationWarningOf('output')
def failed(self, failure): #XXX: Argh. FIXME. failure = str(failure) self.request.write( resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Server Connection Lost", "Connection to distributed server lost:" + html.PRE(failure)).render(self.request)) self.request.finish() log.msg(failure)
def asHTML(self): info = self.asDict() links = [] for file in info['files']: if file['url'] is not None: # could get confused links.append('<a href="%s"><b>%s</b></a>' % (file['url'], file['name'])) else: links.append('<b>%s</b>' % file['name']) if info['revision']: if getattr(self, 'revlink', ""): revision = 'Revision: <a href="%s"><b>%s</b></a>\n' % ( info['revlink'], info['revision']) else: revision = "Revision: <b>%s</b><br />\n" % info['revision'] else: revision = '' if self.repository: repository = "Repository: <b>%s</b><br />\n" % info['repository'] else: repository = '' branch = "" if info['branch']: branch = "Branch: <b>%s</b><br />\n" % info['branch'] properties = [] for prop in info['properties']: properties.append("%s: %s<br />" % (prop[0], prop[1])) kwargs = { 'who' : html.escape(info['who']), 'at' : info['at'], 'files' : html.UL(links) + '\n', 'repository': repository, 'revision' : revision, 'branch' : branch, 'comments' : html.PRE(info['comments']), 'properties': html.UL(properties) + '\n' } return html_tmpl % kwargs
def asHTML(self): links = [] for file in self.files: link = filter(lambda s: s.find(file) != -1, self.links) if len(link) == 1: # could get confused links.append('<a href="%s"><b>%s</b></a>' % (link[0], file)) else: links.append('<b>%s</b>' % file) if self.revision: if getattr(self, 'revlink', ""): revision = 'Revision: <a href="%s"><b>%s</b></a>\n' % ( self.revlink, self.revision) else: revision = "Revision: <b>%s</b><br />\n" % self.revision else: revision = '' if self.repository: repository = "Repository: <b>%s</b><br />\n" % self.repository else: repository = '' branch = "" if self.branch: branch = "Branch: <b>%s</b><br />\n" % self.branch properties = [] for prop in self.properties.asList(): properties.append("%s: %s<br />" % (prop[0], prop[1])) kwargs = { 'who' : html.escape(self.who), 'at' : self.getTime(), 'files' : html.UL(links) + '\n', 'repository': repository, 'revision' : revision, 'branch' : branch, 'comments' : html.PRE(self.comments), 'properties': html.UL(properties) + '\n' } return html_tmpl % kwargs
def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = resrc.render(self) except UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method == b"HEAD") and (b"GET" in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc, )) self.method = b"GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader(b'content-length', intToBytes(len(body))) self._inFakeHead = False self.method = b"HEAD" self.write(b'') self.finish() return if self.method in (supportedMethods): # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(allowedMethods)) s = ('''Your browser approached me (at %(URI)s) with''' ''' the method "%(method)s". I only allow''' ''' the method%(plural)s %(allowed)s here.''' % { 'URI': escape(self.uri), 'method': self.method, 'plural': ((len(allowedMethods) > 1) and 's') or '', 'allowed': ', '.join(allowedMethods) }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (escape(self.method.decode("charmap")), )) body = epage.render(self) # end except UnsupportedMethod if body == NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request did not return bytes", "Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" + "Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" + "Value: " + html.PRE(reflect.safe_repr(body))).render(self) if self.method == b"HEAD": if len(body) > 0: # This is a Bad Thing (RFC 2616, 9.4) log.msg("Warning: HEAD request %s for resource %s is" " returning a message body." " I think I'll eat it." % (self, resrc)) self.setHeader(b'content-length', intToBytes(len(body))) self.write(b'') else: self.setHeader(b'content-length', intToBytes(len(body))) self.write(body) self.finish()
self.filename = filename self.registry = registry def render(self, request): """Render me to a web client. Load my file, execute it in a special namespace (with 'request' and '__file__' global vars) and finish the request. Output to the web-page will NOT be handled with print - standard output goes to the log - but with request.write. """ request.setHeader("x-powered-by", "Twisted/%s" % copyright.version) namespace = { 'request': request, '__file__': self.filename, 'registry': self.registry } try: execfile(self.filename, namespace, namespace) except IOError, e: if e.errno == 2: #file not found request.setResponseCode(http.NOT_FOUND) request.write( resource.NoResource("File not found.").render(request)) except: io = StringIO.StringIO() traceback.print_exc(file=io) request.write(html.PRE(io.getvalue())) request.finish() return server.NOT_DONE_YET
def formatFailure(myFailure): exceptionHTML = """ <p class="error">%s: %s</p> """ frameHTML = """ <div class="location">%s, line %s in <span class="function">%s</span></div> """ snippetLineHTML = """ <div class="snippetLine"><span class="lineno">%s</span><span class="code">%s</span></div> """ snippetHighlightLineHTML = """ <div class="snippetHighlightLine"><span class="lineno">%s</span><span class="code">%s</span></div> """ variableHTML = """ <tr class="varRow"><td class="varName">%s</td><td class="varValue">%s</td></tr> """ if not isinstance(myFailure, failure.Failure): return html.PRE(str(myFailure)) io = StringIO() w = io.write w(stylesheet) w('<a href="#tbend">') w(exceptionHTML % (html.escape(str(myFailure.type)), html.escape(str(myFailure.value)))) w('</a>') w('<div class="stackTrace">') first = 1 for method, filename, lineno, localVars, globalVars in myFailure.frames: if filename == '<string>': continue if first: w('<div class="firstFrame">') first = 0 else: w('<div class="frame">') w(frameHTML % (filename, lineno, method)) w('<div class="snippet">') textSnippet = '' for snipLineNo in range(lineno - 2, lineno + 2): snipLine = linecache.getline(filename, snipLineNo) textSnippet += snipLine snipLine = htmlIndent(snipLine) if snipLineNo == lineno: w(snippetHighlightLineHTML % (snipLineNo, snipLine)) else: w(snippetLineHTML % (snipLineNo, snipLine)) w('</div>') # Instance variables for name, var in localVars: if name == 'self' and hasattr(var, '__dict__'): usedVars = [(key, value) for (key, value) in var.__dict__.items() if _hasSubstring('self.' + key, textSnippet)] if usedVars: w('<div class="variables"><b>Self</b>') w('<table class="variables">') for key, value in usedVars: w(variableHTML % (key, htmlrepr(value))) w('</table></div>') break # Local and global vars for nm, varList in ('Locals', localVars), ('Globals', globalVars): usedVars = [(name, var) for (name, var) in varList if _hasSubstring(name, textSnippet)] if usedVars: w('<div class="variables"><b>%s</b><table class="variables">' % nm) for name, var in usedVars: w(variableHTML % (name, htmlrepr(var))) w('</table></div>') w('</div>') # frame w('</div>') # stacktrace w('<a name="tbend"> </a>') w(exceptionHTML % (html.escape(str(myFailure.type)), html.escape(str(myFailure.value)))) return io.getvalue()
def body(self, req): b = self.builder_status control = self.builder_control status = self.getStatus(req) slaves = b.getSlaves() connected_slaves = [s for s in slaves if s.isConnected()] projectName = status.getProjectName() data = '<a href="%s">%s</a>\n' % (self.path_to_root(req), projectName) data += "<h1>Builder: %s</h1>\n" % html.escape(b.getName()) # the first section shows builds which are currently running, if any. current = b.getCurrentBuilds() if current: data += "<h2>Currently Building:</h2>\n" data += "<ul>\n" for build in current: data += " <li>" + self.build_line(build, req) + "</li>\n" data += "</ul>\n" else: data += "<h2>no current builds</h2>\n" # Then a section with the last 5 builds, with the most recent build # distinguished from the rest. data += "<h2>Recent Builds:</h2>\n" data += "<ul>\n" for i, build in enumerate(b.generateFinishedBuilds(num_builds=5)): data += " <li>" + self.make_line(req, build, False) + "</li>\n" if i == 0: data += "<br />\n" # separator # TODO: or empty list? data += "</ul>\n" data += "<h2>Buildslaves:</h2>\n" data += "<ol>\n" for slave in slaves: slaveurl = path_to_slave(req, slave) data += "<li><b><a href=\"%s\">%s</a></b>: " % ( html.escape(slaveurl), html.escape(slave.getName())) if slave.isConnected(): data += "CONNECTED\n" if slave.getAdmin(): data += make_row("Admin:", html.escape(slave.getAdmin())) if slave.getHost(): data += "<span class='label'>Host info:</span>\n" data += html.PRE(slave.getHost()) else: data += ("NOT CONNECTED\n") data += "</li>\n" data += "</ol>\n" if control is not None and connected_slaves: forceURL = urllib.quote(req.childLink("force")) data += make_force_build_form(forceURL) elif control is not None: data += """ <p>All buildslaves appear to be offline, so it's not possible to force this build to execute at this time.</p> """ if control is not None: pingURL = urllib.quote(req.childLink("ping")) data += """ <form action="%s" class='command pingbuilder'> <p>To ping the buildslave(s), push the 'Ping' button</p> <input type="submit" value="Ping Builder" /> </form> """ % pingURL # TODO: this stuff should be generated by a template of some sort projectURL = status.getProjectURL() projectName = status.getProjectName() data += '<hr /><div class="footer">\n' welcomeurl = self.path_to_root(req) + "index.html" data += '[<a href="%s">welcome</a>]\n' % welcomeurl data += "<br />\n" data += '<a href="http://buildbot.sourceforge.net/">Buildbot</a>' data += "-%s " % version if projectName: data += "working for the " if projectURL: data += "<a href=\"%s\">%s</a> project." % (projectURL, projectName) else: data += "%s project." % projectName data += "<br />\n" data += ("Page built: " + time.strftime( "%a %d %b %Y %H:%M:%S", time.localtime(util.now())) + "\n") data += '</div>\n' return data
def body(self, req): b = self.builder_status control = self.builder_control status = self.getStatus(req) slaves = b.getSlaves() connected_slaves = [s for s in slaves if s.isConnected()] projectName = status.getProjectName() data = '' # the first section shows builds which are currently running, if any. current = b.getCurrentBuilds() if current: data += "<h2>Currently Building:</h2>\n" data += "<ul>\n" for build in current: data += " <li>" + self.build_line(build, req) + "</li>\n" data += "</ul>\n" else: data += "<h2>No current builds</h2>\n" # Then a section with the last 5 builds, with the most recent build # distinguished from the rest. data += "<h2>Recent Builds</h2>\n" data += "<ul>\n" numbuilds = int(req.args.get('numbuilds', ['5'])[0]) for i, build in enumerate( b.generateFinishedBuilds(num_builds=int(numbuilds))): data += " <li>" + self.make_line(req, build, False) + "</li>\n" if i == 0: data += "<br />\n" # separator # TODO: or empty list? data += "</ul>\n" data += "<h2>Buildslaves:</h2>\n" data += "<ol>\n" for slave in slaves: slaveurl = path_to_slave(req, slave) data += "<li><b><a href=\"%s\">%s</a></b>: " % ( html.escape(slaveurl), html.escape(slave.getName())) if slave.isConnected(): data += "CONNECTED\n" if slave.getAdmin(): data += make_row("Admin:", html.escape(slave.getAdmin())) if slave.getHost(): data += "<span class='label'>Host info:</span>\n" data += html.PRE(html.escape(slave.getHost())) else: data += ("NOT CONNECTED\n") data += "</li>\n" data += "</ol>\n" if control is not None and connected_slaves: forceURL = path_to_builder(req, b) + '/force' data += make_force_build_form(forceURL, self.isUsingUserPasswd(req)) elif control is not None: data += """ <p>All buildslaves appear to be offline, so it's not possible to force this build to execute at this time.</p> """ if control is not None: pingURL = path_to_builder(req, b) + '/ping' data += """ <form method="post" action="%s" class='command pingbuilder'> <p>To ping the buildslave(s), push the 'Ping' button</p> <input type="submit" value="Ping Builder" /> </form> """ % pingURL return data
def body(self, req): """ Overriden method from builders.StatusResourceBuilder. The only change in original behavior is added new checkbox for clobbering.""" b = self.builder_status control = self.builder_control status = self.getStatus(req) slaves = b.getSlaves() connected_slaves = [s for s in slaves if s.isConnected()] projectName = status.getProjectName() data = '<a href="%s">%s</a>\n' % (self.path_to_root(req), projectName) data += ( '<h1><a href="%swaterfall?builder=%s">Builder: %s</a></h1>\n' % (self.path_to_root(req), urllib.quote( b.getName(), safe=''), html.escape(b.getName()))) # the first section shows builds which are currently running, if any. current = b.getCurrentBuilds() if current: data += "<h2>Currently Building:</h2>\n" data += "<ul>\n" for build in current: data += " <li>" + self.build_line(build, req) + "</li>\n" data += "</ul>\n" else: data += "<h2>no current builds</h2>\n" # Then a section with the last 5 builds, with the most recent build # distinguished from the rest. data += "<h2>Recent Builds:</h2>\n" data += "<ul>\n" for i, build in enumerate(b.generateFinishedBuilds(num_builds=5)): data += " <li>" + self.make_line(req, build, False) + "</li>\n" if i == 0: data += "<br />\n" # separator # TODO: or empty list? data += "</ul>\n" data += "<h2>Buildslaves:</h2>\n" data += "<ol>\n" for slave in slaves: name = slave.getName() if not name: name = '' data += "<li><b>%s</b>: " % html.escape(name) if slave.isConnected(): data += "CONNECTED\n" if slave.getAdmin(): data += make_row("Admin:", html.escape(slave.getAdmin())) if slave.getHost(): data += "<span class='label'>Host info:</span>\n" data += html.PRE(slave.getHost()) else: data += ("NOT CONNECTED\n") data += "</li>\n" data += "</ol>\n" if control is not None and connected_slaves: forceURL = urllib.quote(req.childLink("force")) data += (""" <form action='%(forceURL)s' class='command forcebuild'> <p>To force a build, fill out the following fields and push the 'Force Build' button</p> <table> <tr class='row' valign="bottom"> <td> <span class="label">Your name<br> (<span style="color: red;">please fill in at least this much</span>):</span> </td> <td> <span class="field"><input type='text' name='username' /></span> </td> </tr> <tr class='row'> <td> <span class="label">Reason for build:</span> </td> <td> <span class="field"><input type='text' name='comments' /></span> </td> </tr> <tr class='row'> <td> <span class="label">Branch to build:</span> </td> <td> <span class="field"><input type='text' name='branch' /></span> </td> </tr> <tr class='row'> <td> <span class="label">Revision to build:</span> </td> <td> <span class="field"><input type='text' name='revision' /></span> </td> </tr> <tr class='row'> <td> <span class="label">Slave to use:</span> </td> <td> <span class="field"><input type='text' name='slavename' /></span> </td> </tr> <tr class='row'> <td> <span class="label">Clobber:</span> </td> <td> <span class="field"><input type='checkbox' name='clobber' /> </span> </td> </tr> </table> <input type='submit' value='Force Build' /> </form> """) % { "forceURL": forceURL } elif control is not None: data += """ <p>All buildslaves appear to be offline, so it's not possible to force this build to execute at this time.</p> """ if control is not None: pingURL = urllib.quote(req.childLink("ping")) data += """ <form action="%s" class='command pingbuilder'> <p>To ping the buildslave(s), push the 'Ping' button</p> <input type="submit" value="Ping Builder" /> </form> """ % pingURL return data
class CDelayRequest(Request): def __init__(self, *args, **kw): Request.__init__(self, *args, **kw) #渲染,继承自Request def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = resrc.render(self) except UnsupportedMethod, e: sAllowedMethodList = e.allowedMethods if (self.method == "HEAD") and ("GET" in sAllowedMethodList): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.Info("Using GET to fake a HEAD request for %s" % resrc) self.method = "GET" #来自http.Request self._inFakeHead = True #来自web.server.Request body = resrc.render(self) if body is NOT_DONE_YET: log.Info("Tried to fake a HEAD request for %s, but it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader("content-length", str(len(body))) self._inFakeHead = False self.method = "HEAD" self.write("") self.finish() return if self.method in SUPPORT_METHOD_LIST: # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(sAllowedMethodList)) s = ("""Your browser approached me (at %(URI)s) with""" """ the method "%(method)s". I only allow""" """ the method%(plural)s %(allowed)s here.""" % { "URI" : escape(self.uri), "method" : self.method, "plural" : ((len(sAllowedMethodList) > 1) and "s") or "", "allowed" : string.join(sAllowedMethodList, ", ") }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (escape(self.method),)) body = epage.render(self) # end except UnsupportedMethod if body == NOT_DONE_YET: return if not isinstance(body, defer.Deferred) and type(body) is not types.StringType: body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request did not return a string", "Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" + "Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" + "Value: " + html.PRE(reflect.safe_repr(body))).render(self) if self.method == "HEAD": if len(body) > 0: # This is a Bad Thing (RFC 2616, 9.4) log.Info("Warning: HEAD request %s for resource %s is" " returning a message body." " I think I'll eat it." % (self, resrc)) self.setHeader("content-length", str(len(body))) self.write("") self.finish() else: if isinstance(body, defer.Deferred): body.addCallback(self.DeferWrite) else: self.setHeader("content-length", str(len(body))) self.write(body) self.finish()