def render(self, request): """ render() is called when the script_runner has its newjob method invoked. This is the start of the job execution process.""" log.msg(request, level='minor') log.msg(request.args, level='minor') if request.path == "/newjob": new_job_id = request.args["jobhref"][0] log.msg("Received request to initiate job with href: " + new_job_id, level='major') job_rec = {"job_identity": new_job_id} # Invoke the status method with the new_job_id. This call will start the # process of gathering information about the job to be executed. yield self.script_runner.initiate(job_rec) defer.returnValue( tw2http.Response( 200, {'content-type': http_headers.MimeType('text', 'plain')}, "Job Initiated")) else: defer.returnValue( tw2http.Response( 404, {'content-type': http_headers.MimeType('text', 'plain')}, "No matching resource."))
def testContentType(self): table = ( ("text/html;charset=iso-8859-4", http_headers.MimeType('text', 'html', (('charset', 'iso-8859-4'), ))), ("text/html", http_headers.MimeType('text', 'html')), ) self.runRoundtripTest("Content-Type", table)
def test_dataState(self): """ Test the internal state of the Data object """ self.assert_(hasattr(self.data, "created_time")) self.assertEquals(self.data.data, self.text) self.assertEquals(self.data.type, http_headers.MimeType("text", "plain")) self.assertEquals(self.data.contentType(), http_headers.MimeType("text", "plain"))
def render(self, ctx): """Render a web page with descriptive statistics.""" if self.manager: return http.Response( 200, {'content-type': http_headers.MimeType('text', 'html')}, self.manager.getStats()) else: return http.Response( 200, {'content-type': http_headers.MimeType('text', 'html')}, '<html><body><p>Some Statistics</body></html>')
def uploadFile(self, fieldname, filename, mimetype, content, resrc=None, host='foo', path='/'): if not resrc: resrc = self.root ctype = http_headers.MimeType('multipart', 'form-data', (('boundary', '---weeboundary'), )) return self.getResponseFor(resrc, '/', headers={ 'host': 'foo', 'content-type': ctype }, length=len(content), method='POST', content="""-----weeboundary\r Content-Disposition: form-data; name="%s"; filename="%s"\r Content-Type: %s\r \r %s\r -----weeboundary--\r """ % (fieldname, filename, mimetype, content))
def render(self, request): title = "Directory listing for %s" % urllib.unquote(request.path) s = """<html><head><title>%s</title><style> th, .even td, .odd td { padding-right: 0.5em; font-family: monospace} .even-dir { background-color: #efe0ef } .even { background-color: #eee } .odd-dir {background-color: #f0d0ef } .odd { background-color: #dedede } .icon { text-align: center } .listing { margin-left: auto; margin-right: auto; width: 50%%; padding: 0.1em; } body { border: 0; padding: 0; margin: 0; background-color: #efefef;} h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;} </style></head><body><div class="directory-listing"><h1>%s</h1>""" % (title, title) s += "<table>" s += "<tr><th>Filename</th><th>Size</th><th>Last Modified</th><th>File Type</th></tr>" even = False for row in self.data_listing(request, None): s += '<tr class="%s">' % (even and 'even' or 'odd', ) s += '<td><a href="%(link)s">%(linktext)s</a></td><td align="right">%(size)s</td><td>%(lastmod)s</td><td>%(type)s</td></tr>' % row even = not even s += "</table></div></body></html>" response = http.Response(200, {}, s) response.headers.setHeader("content-type", http_headers.MimeType('text', 'html')) return response
def test_maxFields(self): """ Check that the C{maxSize} parameter makes the parsing raise an exception if the data contains too many fields. """ ctype = http_headers.MimeType('multipart', 'form-data', (('boundary', '---xyz'),)) content = """-----xyz\r Content-Disposition: form-data; name="foo"\r \r Foo Bar\r -----xyz\r Content-Disposition: form-data; name="foo"\r \r Baz\r -----xyz\r Content-Disposition: form-data; name="file"; filename="filename"\r Content-Type: text/html\r \r blah\r -----xyz\r Content-Disposition: form-data; name="file"; filename="filename"\r Content-Type: text/plain\r \r bleh\r -----xyz--\r """ root = resource.Resource() request = SimpleRequest(server.Site(root), "GET", "/", http_headers.Headers({'content-type': ctype}), content) def cb(res): self.assertEquals(res.response.description, "Maximum number of fields 3 exceeded") return self.assertFailure(server.parsePOSTData(request, maxFields=3), http.HTTPError).addCallback(cb)
def __init__(self, msg="", content_type=None): self.msg = msg response = Response(404, stream=msg) if content_type is None: content_type = http_headers.MimeType("text", "plain") response.headers.setHeader("content-type", content_type) HTTPError.__init__(self, response)
def render(self, request): code = request.args.get('code')[0] print code result = sage0.sage0.eval(code) print result return http.Response(200, {'content-type': http_headers.MimeType( \ 'text', 'html')}, result)
def cb(ign): self.assertEquals(request.args, {}) self.assertEquals(request.files.keys(), ['FileNameOne']) self.assertEquals(request.files.values()[0][0][:2], ('myfilename', http_headers.MimeType('text', 'html', {}))) f = request.files.values()[0][0][2] self.assertEquals(f.read(), "my great content wooo")
def render(self, r): view_w, view_h = VIEW_SIZE start_row, start_col = START_POS end_row = start_row + view_h end_col = start_col + view_w tile_w, tile_h = TILE_SIZE tpl = templates.get_template("index.myt") try: data = tpl.render( viewport_width=view_w, viewport_height=view_h, start_col=start_col, start_row=start_row, tile_width=tile_w, tile_height=tile_h, initial_zoom=INITIAL_ZOOM, zoom_min=ZOOM_MIN, zoom_max=ZOOM_MAX, mode=mode.__name__, ) response = responsecode.OK except: data = exceptions.html_error_template().render() response = responsecode.INTERNAL_SERVER_ERROR return http.Response( response, { 'Content-Type': http_headers.MimeType('text', 'html', [('charset', 'utf-8')]) }, data)
def defaultErrorHandler(request, response): if response.stream is not None: # Already got an error message return response if response.code < 300: # We only do error messages return response message = ERROR_MESSAGES.get(response.code, None) if message is None: # No message specified for that code return response message = message % { 'uri':_escape(request.uri), 'location':_escape(response.headers.getHeader('location')), 'method':_escape(request.method) } title = RESPONSES.get(response.code, "") body = ("<html><head><title>%d %s</title></head>" "<body><h1>%s</h1>%s</body></html>") % ( response.code, title, title, message) response.headers.setHeader("content-type", http_headers.MimeType('text', 'html')) response.stream = stream.MemoryStream(body) return response
def __init__(self, code, description, title=None): """ @param code: a response code in L{responsecode.RESPONSES}. @param description: a string description. @param title: the message title. If not specified or C{None}, defaults to C{responsecode.RESPONSES[code]}. """ if title is None: title = cgi.escape(responsecode.RESPONSES[code]) output = "".join(( "<html>", "<head>", "<title>%s</title>" % (title,), "</head>", "<body>", "<h1>%s</h1>" % (title,), "<p>%s</p>" % (cgi.escape(description),), "</body>", "</html>", )) if type(output) == unicode: output = output.encode("utf-8") mime_params = {"charset": "utf-8"} else: mime_params = {} super(StatusResponse, self).__init__(code=code, stream=output) self.headers.setHeader("content-type", http_headers.MimeType("text", "html", mime_params)) self.description = description
def render(self, ctx): return http.Response( 200, { 'content-type': http_headers.MimeType( 'text', 'html') }, '<html><body>\n\n' + self.manager.getStats() + '\n</body></html>\n')
def test_multipart(self): """ Test parsing data in multipart format: it should fill the C{files} attribute. """ ctype = http_headers.MimeType('multipart', 'form-data', (('boundary', '---weeboundary'),)) content="""-----weeboundary\r Content-Disposition: form-data; name="FileNameOne"; filename="myfilename"\r Content-Type: text/html\r \r my great content wooo\r -----weeboundary--\r """ root = resource.Resource() request = SimpleRequest(server.Site(root), "GET", "/", http_headers.Headers({'content-type': ctype}), content) def cb(ign): self.assertEquals(request.args, {}) self.assertEquals(request.files.keys(), ['FileNameOne']) self.assertEquals(request.files.values()[0][0][:2], ('myfilename', http_headers.MimeType('text', 'html', {}))) f = request.files.values()[0][0][2] self.assertEquals(f.read(), "my great content wooo") return server.parsePOSTData(request).addCallback(cb)
def _make_page(parent, name, text, content_type="text/html", leaf=False): page = Page() page.text = text base_type, specific_type = content_type.split("/") page.content_type = http_headers.MimeType(base_type, specific_type) page.addSlash = not leaf setattr(parent, "child_" + name, page) return page
class Page(resource.Resource): addSlash = True content_type = http_headers.MimeType("text", "html") def render(self, ctx): return http.Response(responsecode.OK, {"content-type": self.content_type}, self.text)
def _make_page(parent, name, text, content_type, wrapper, leaf=False): page = Page() page.text = text base_type, specific_type = content_type.split("/") page.content_type = http_headers.MimeType(base_type, specific_type) page.addSlash = not leaf parent.putChild(name, wrapper(page)) return page
def check_result(response): response = IResponse(response) if response.code != responsecode.MULTI_STATUS: self.fail("Incorrect response code for PROPFIND (%s != %s)" % (response.code, responsecode.MULTI_STATUS)) content_type = response.headers.getHeader("content-type") if content_type not in (http_headers.MimeType("text", "xml"), http_headers.MimeType( "application", "xml")): self.fail( "Incorrect content-type for PROPFIND response (%r not in %r)" % (content_type, (http_headers.MimeType("text", "xml"), http_headers.MimeType("application", "xml")))) return davXMLFromStream(response.stream).addCallback(check_xml)
def renderHTTP_exception(self, req, reason): response = http.Response( responsecode.INTERNAL_SERVER_ERROR, {'content-type': http_headers.MimeType('text','plain')}, ("An error occurred while processing the request. " "More information is available in the server log.")) log_error(req, response, reason) return response
def render(self, request): # For GET/HEAD: Return an error message s = ( "<html><head><title>XML-RPC responder</title></head>" "<body><h1>XML-RPC responder</h1>POST your XML-RPC here.</body></html>" ) return http.Response( responsecode.OK, {'content-type': http_headers.MimeType('text', 'html')}, s)
def testEquality(self): """Test that various uses of the constructer are equal """ kwargMime = http_headers.MimeType('text', 'plain', key='value', param=None) dictMime = http_headers.MimeType('text', 'plain', {'param': None, 'key': 'value'}) tupleMime = http_headers.MimeType('text', 'plain', (('param', None), ('key', 'value'))) stringMime = http_headers.MimeType.fromString('text/plain;key=value;param') self.assertEquals(kwargMime, dictMime) self.assertEquals(dictMime, tupleMime) self.assertEquals(kwargMime, tupleMime) self.assertEquals(kwargMime, stringMime)
def test_wrongContentType(self): """ Check that a content-type not handled raise a C{http.HTTPError}. """ ctype = http_headers.MimeType('application', 'foobar') content = "key=value&multiple=two+words&multiple=more%20words" root = resource.Resource() request = SimpleRequest(server.Site(root), "GET", "/", http_headers.Headers({'content-type': ctype}), content) return self.assertFailure(server.parsePOSTData(request), http.HTTPError)
def _cbRender(self, result, request): if not isinstance(result, Fault): result = (result, ) try: s = xmlrpclib.dumps(result, methodresponse=1) except: f = Fault(self.FAILURE, "can't serialize output") s = xmlrpclib.dumps(f, methodresponse=1) return http.Response( responsecode.OK, {'content-type': http_headers.MimeType('text', 'xml')}, s)
def renderHTTP_exception(self, req, reason): log.msg("Exception rendering:", isErr=1) log.err(reason) body = ( "<html><head><title>Internal Server Error</title></head>" "<body><h1>Internal Server Error</h1>An error occurred rendering the requested page. More information is available in the server log.</body></html>" ) return http.Response( responsecode.INTERNAL_SERVER_ERROR, {'content-type': http_headers.MimeType('text', 'html')}, body)
class Child(resource.Resource): creation_time = time.time() text = 'Yo Ho Ho and a bottle of rum.' content_type = http_headers.MimeType('text', 'plain') def render(self, ctx): return http.Response( responsecode.OK, { 'last-modified': self.creation_time, 'etag': http_headers.ETag(str(hash(self.text))), 'content-type': self.content_type }, self.text)
def _respond(self, image_data): return http.Response( responsecode.OK, { 'Content-Type': http_headers.MimeType('image', 'png'), # Not cacheable 'Cache-Control': { 'no-store': None }, 'Expires': 100, }, stream.MemoryStream(image_data))
def doTrace(request): request = iweb.IRequest(request) txt = "%s %s HTTP/%d.%d\r\n" % (request.method, request.uri, request.clientproto[0], request.clientproto[1]) l = [] for name, valuelist in request.headers.getAllRawHeaders(): for value in valuelist: l.append("%s: %s\r\n" % (name, value)) txt += ''.join(l) return http.Response( responsecode.OK, {'content-type': http_headers.MimeType('message', 'http')}, txt)
def _processingReallyFailed(self, reason, origReason): log.msg("Exception rendering error page:", isErr=1) log.err(reason) log.msg("Original exception:", isErr=1) log.err(origReason) body = ( "<html><head><title>Internal Server Error</title></head>" "<body><h1>Internal Server Error</h1>An error occurred rendering the requested page. Additionally, an error occured rendering the error page.</body></html>" ) response = http.Response( responsecode.INTERNAL_SERVER_ERROR, {'content-type': http_headers.MimeType('text', 'html')}, body) self.writeResponse(response)
def test_urlencoded(self): """ Test parsing data in urlencoded format: it should end in the C{args} attribute. """ ctype = http_headers.MimeType('application', 'x-www-form-urlencoded') content = "key=value&multiple=two+words&multiple=more%20words" root = resource.Resource() request = SimpleRequest(server.Site(root), "GET", "/", http_headers.Headers({'content-type': ctype}), content) def cb(ign): self.assertEquals(request.files, {}) self.assertEquals(request.args, {'multiple': ['two words', 'more words'], 'key': ['value']}) return server.parsePOSTData(request).addCallback(cb)