def renderHTTP(self, request): """ See L{iweb.IResource.renderHTTP}. This implementation will dispatch the given C{request} to another method of C{self} named C{http_}METHOD, where METHOD is the HTTP method used by C{request} (eg. C{http_GET}, C{http_POST}, etc.). Generally, a subclass should implement those methods instead of overriding this one. C{http_*} methods are expected provide the same interface and return the same results as L{iweb.IResource}C{.renderHTTP} (and therefore this method). C{etag} and C{last-modified} are added to the response returned by the C{http_*} header, if known. If an appropriate C{http_*} method is not found, a L{responsecode.NOT_ALLOWED}-status response is returned, with an appropriate C{allow} header. @param request: the request to process. @return: an object adaptable to L{iweb.IResponse}. """ method = getattr(self, 'http_' + request.method, None) if not method: response = http.Response(responsecode.NOT_ALLOWED) response.headers.setHeader("allow", self.allowedMethods()) return response d = self.checkPreconditions(request) if d is None: return method(request) else: return d.addCallback(method)
def packageSuccess(self, result): headers, data = httputil.serialize(result) response = http.Response(200, stream=stream.MemoryStream(data)) for k, v in headers.iteritems(): response.headers.addRawHeader(k, v) response.headers.setHeader('content-type', http_headers.MimeType('text', 'plain')) return response
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 render(self, request): for filterscript in self.filters: if os.path.exists(filterscript): return runCGI(request, self.filename, filterscript) else: log.err(self.__class__.__name__ + ' could not find any of: ' + ', '.join(self.filters)) return http.Response(responsecode.INTERNAL_SERVER_ERROR)
def __init__(self, request): from ipython1.external.twisted.web2 import http components.Componentized.__init__(self) self.request = request self.response = http.Response(stream=stream.ProducerStream()) # This deferred will be fired by the first call to write on OldRequestAdapter # and will cause the headers to be output. self.deferredResponse = defer.Deferred()
def packageFailure(self, f): f.cleanFailure() headers, data = httputil.serialize(f) response = http.Response(200, stream=stream.MemoryStream(data)) for k, v in headers.iteritems(): response.headers.addRawHeader(k, v) response.headers.setHeader('content-type', http_headers.MimeType('text', 'plain')) return response
def packageFailure(self, f): f.cleanFailure() print "Failing:\n" + f.getTraceback() data = simplejson.dumps(jsonifyFailure(f)) response = http.Response(200, stream=stream.MemoryStream(data)) response.headers.setHeader('content-type', http_headers.MimeType('text', 'plain')) return response
def http_OPTIONS(self, request): """ Respond to a OPTIONS request. @param request: the request to process. @return: an object adaptable to L{iweb.IResponse}. """ response = http.Response(responsecode.OK) response.headers.setHeader("allow", self.allowedMethods()) 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 processEnded(self, reason): if reason.value.exitCode != 0: log.msg("CGI %s exited with exit code %s" % (self.request.uri, reason.value.exitCode)) if self.errortext: log.msg("Errors from CGI %s: %s" % (self.request.uri, self.errortext)) if self.handling_headers: log.msg("Premature end of headers in %s: %s" % (self.request.uri, self.headertext)) self.response = http.Response(responsecode.INTERNAL_SERVER_ERROR) self._sendResponse() self.stream.finish()
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)
def preprocessRequest(self): """Do any request processing that doesn't follow the normal resource lookup procedure. "OPTIONS *" is handled here, for example. This would also be the place to do any CONNECT processing.""" if self.method == "OPTIONS" and self.uri == "*": response = http.Response(responsecode.OK) response.headers.setHeader('allow', ('GET', 'HEAD', 'OPTIONS', 'TRACE')) return response # This is where CONNECT would go if we wanted it return None
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 startWSGIResponse(self, status, response_headers, exc_info=None): # Called in application thread if exc_info is not None: try: if self.headersSent: raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None elif self.response is not None: raise AlreadyStartedResponse, 'startWSGIResponse(%r)' % status status = int(status.split(' ')[0]) self.response = http.Response(status) for key, value in response_headers: self.response.headers.addRawHeader(key, value) return self.write
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)
class HTTPNotebookBaseMethod(resource.Resource): def __init__(self, nbc): self.nbc = nbc log.msg("Creating child resource...") def locateChild(self, request, segments): return self, () def renderHTTP(self, request): print request, request.args return http.Response(200, stream=stream.MemoryStream(repr(request))) def buildRequestSummary(self, request): reply = """host: %r port: %r path: %r prepath: %r postpath: %r args: %r method: %r headers: %r """ % (request.host, request.port, request.path, request.prepath, request.postpath, request.args, request.method, request.headers) return reply def packageSuccess(self, result, justme=False): print result try: if isinstance(result, type(None)): data = "" elif isinstance(result, list): data = simplejson.dumps({ 'list': [r.jsonify(keepdict=True, justme=justme) for r in result] }) else: data = result.jsonify(justme=justme) except AttributeError, e: raise e # data = simplejson.dumps(result) response = http.Response(200, stream=stream.MemoryStream(data)) response.headers.setHeader('content-type', http_headers.MimeType('text', 'plain')) return response
def runCGI(request, filename, filterscript=None): # Make sure that we don't have an unknown content-length if request.stream.length is None: return http.Response(responsecode.LENGTH_REQUIRED) env = createCGIEnvironment(request) env['SCRIPT_FILENAME'] = filename if '=' in request.querystring: qargs = [] else: qargs = [urllib.unquote(x) for x in request.querystring.split('+')] if filterscript is None: filterscript = filename qargs = [filename] + qargs else: qargs = [filterscript, filename] + qargs d = defer.Deferred() proc = CGIProcessProtocol(request, d) reactor.spawnProcess(proc, filterscript, qargs, env, os.path.dirname(filename)) return d
def __init__(self, request, deferred): self.request = request self.deferred = deferred self.stream = stream.ProducerStream() self.response = http.Response(stream=self.stream)
def render(self, req): return http.Response( responsecode.OK, http_headers.Headers({'content-type': self.contentType()}), stream=self.data)
def renderHTTP(self, request): return http.Response(200, stream=stream.MemoryStream(repr(request)))
class File(StaticRenderMixin): """ File is a resource that represents a plain non-interpreted file (although it can look for an extension like .rpy or .cgi and hand the file to a processor for interpretation if you wish). Its constructor takes a file path. Alternatively, you can give a directory path to the constructor. In this case the resource will represent that directory, and its children will be files underneath that directory. This provides access to an entire filesystem tree with a single Resource. If you map the URL 'http://server/FILE' to a resource created as File('/tmp'), then http://server/FILE/ will return an HTML-formatted listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will return the contents of /tmp/foo/bar.html . """ implements(iweb.IResource) def _getContentTypes(self): if not hasattr(File, "_sharedContentTypes"): File._sharedContentTypes = loadMimeTypes() return File._sharedContentTypes contentTypes = property(_getContentTypes) contentEncodings = { ".gz" : "gzip", ".bz2": "bzip2" } processors = {} indexNames = ["index", "index.html", "index.htm", "index.trp", "index.rpy"] type = None def __init__(self, path, defaultType="text/plain", ignoredExts=(), processors=None, indexNames=None): """Create a file with the given path. """ super(File, self).__init__() self.putChildren = {} self.fp = filepath.FilePath(path) # Remove the dots from the path to split self.defaultType = defaultType self.ignoredExts = list(ignoredExts) if processors is not None: self.processors = dict([ (key.lower(), value) for key, value in processors.items() ]) if indexNames is not None: self.indexNames = indexNames def exists(self): return self.fp.exists() def etag(self): if not self.fp.exists(): return None st = self.fp.statinfo # # Mark ETag as weak if it was modified more recently than we can # measure and report, as it could be modified again in that span # and we then wouldn't know to provide a new ETag. # weak = (time.time() - st.st_mtime <= 1) return http_headers.ETag( "%X-%X-%X" % (st.st_ino, st.st_size, st.st_mtime), weak=weak ) def lastModified(self): if self.fp.exists(): return self.fp.getmtime() else: return None def creationDate(self): if self.fp.exists(): return self.fp.getmtime() else: return None def contentLength(self): if self.fp.exists(): if self.fp.isfile(): return self.fp.getsize() else: # Computing this would require rendering the resource; let's # punt instead. return None else: return None def _initTypeAndEncoding(self): self._type, self._encoding = getTypeAndEncoding( self.fp.basename(), self.contentTypes, self.contentEncodings, self.defaultType ) # Handle cases not covered by getTypeAndEncoding() if self.fp.isdir(): self._type = "httpd/unix-directory" def contentType(self): if not hasattr(self, "_type"): self._initTypeAndEncoding() return http_headers.MimeType.fromString(self._type) def contentEncoding(self): if not hasattr(self, "_encoding"): self._initTypeAndEncoding() return self._encoding def displayName(self): if self.fp.exists(): return self.fp.basename() else: return None def ignoreExt(self, ext): """Ignore the given extension. Serve file.ext if file is requested """ self.ignoredExts.append(ext) def directoryListing(self): return dirlist.DirectoryLister(self.fp.path, self.listChildren(), self.contentTypes, self.contentEncodings, self.defaultType) def putChild(self, name, child): """ Register a child with the given name with this resource. @param name: the name of the child (a URI path segment) @param child: the child to register """ self.putChildren[name] = child def getChild(self, name): """ Look up a child resource. @return: the child of this resource with the given name. """ if name == "": return self child = self.putChildren.get(name, None) if child: return child child_fp = self.fp.child(name) if child_fp.exists(): return self.createSimilarFile(child_fp.path) else: return None def listChildren(self): """ @return: a sequence of the names of all known children of this resource. """ children = self.putChildren.keys() if self.fp.isdir(): children += [c for c in self.fp.listdir() if c not in children] return children def locateChild(self, req, segments): """ See L{IResource}C{.locateChild}. """ # If getChild() finds a child resource, return it child = self.getChild(segments[0]) if child is not None: return (child, segments[1:]) # If we're not backed by a directory, we have no children. # But check for existance first; we might be a collection resource # that the request wants created. self.fp.restat(False) if self.fp.exists() and not self.fp.isdir(): return (None, ()) # OK, we need to return a child corresponding to the first segment path = segments[0] if path: fpath = self.fp.child(path) else: # Request is for a directory (collection) resource return (self, server.StopTraversal) # Don't run processors on directories - if someone wants their own # customized directory rendering, subclass File instead. if fpath.isfile(): processor = self.processors.get(fpath.splitext()[1].lower()) if processor: return ( processor(fpath.path), segments[1:]) elif not fpath.exists(): sibling_fpath = fpath.siblingExtensionSearch(*self.ignoredExts) if sibling_fpath is not None: fpath = sibling_fpath return self.createSimilarFile(fpath.path), segments[1:] def renderHTTP(self, req): self.fp.restat(False) return super(File, self).renderHTTP(req) def render(self, req): """You know what you doing.""" if not self.fp.exists(): return responsecode.NOT_FOUND if self.fp.isdir(): if req.uri[-1] != "/": # Redirect to include trailing '/' in URI return http.RedirectResponse(req.unparseURL(path=req.path+'/')) else: ifp = self.fp.childSearchPreauth(*self.indexNames) if ifp: # Render from the index file standin = self.createSimilarFile(ifp.path) else: # Render from a DirectoryLister standin = dirlist.DirectoryLister( self.fp.path, self.listChildren(), self.contentTypes, self.contentEncodings, self.defaultType ) return standin.render(req) try: f = self.fp.open() except IOError, e: import errno if e[0] == errno.EACCES: return responsecode.FORBIDDEN elif e[0] == errno.ENOENT: return responsecode.NOT_FOUND else: raise response = http.Response() response.stream = stream.FileStream(f, 0, self.fp.getsize()) for (header, value) in ( ("content-type", self.contentType()), ("content-encoding", self.contentEncoding()), ): if value is not None: response.headers.setHeader(header, value) return response
def doSCGI(request, host, port): if request.stream.length is None: return http.Response(responsecode.LENGTH_REQUIRED) factory = SCGIClientProtocolFactory(request) reactor.connectTCP(host, port, factory) return factory.deferred
def sendFailureResponse(self, reason): response = http.Response(code=responsecode.BAD_GATEWAY, stream=str(reason.value)) self.deferred.callback(response)
def renderHTTP(self, req): return http.Response(responsecode.NOT_FOUND)
def createRequest(self): self.stream = stream_mod.ProducerStream(self.length) self.response = http.Response(self.code, self.inHeaders, self.stream) self.stream.registerProducer(self, True) del self.inHeaders
def render(self, req): return http.Response( 200, stream="I am a very simple resource, a pluggable resource too")
def render(self, req): return http.Response(404, stream="No Such Plugin %s" % self.plugin)
def render(self, request): errormsg = 'CGI directories do not support directory listing' return http.Response(responsecode.FORBIDDEN)
def _sparse(nb): data = str(nb[0].sparse()) response = http.Response(200, stream=stream.MemoryStream(data)) response.headers.setHeader('content-type', http_headers.MimeType('text', 'plain')) return response