def _respond(self, vehicles): json = simplejson.dumps(vehicles) r = http.Response( responsecode.OK, { 'Content-Type': http_headers.MimeType('text', 'javascript'), # Not cacheable 'Cache-Control': { 'no-store': None }, 'Expires': 100, }, stream.MemoryStream(json)) r.headers.addRawHeader('X-JSON', json) return r
def render(self, request): title = "Directory listing for %s" % urllib.unquote(request.path) # TODO we need a better way to transform between url paths and file paths... pathSegments = ["/"] + urllib.unquote(request.path.strip("/")).split( os.sep) linkTargets = ["/"] accumulated = "/" for segment in pathSegments[1:]: accumulated += urllib.quote(segment) + "/" linkTargets.append(accumulated) linkList = '<a href="%s">%s</a>' % ("/", nodename) + "/" + \ "/".join(['<a href="%s">%s</a>' % (linkTarget, pathSegment) for (linkTarget, pathSegment) in zip(linkTargets[1:], pathSegments[1:]) ]) s = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">""" s += htmlHead(title) s += """<body> <div id="content"> <h1 class="rechts"> <a href="http://www.missioneternity.org/"> <img src="http://www.missioneternity.org/themes/m221e/images/m221e-logo2-o.gif" alt="" border="0" /> </a> </h1>""" s += showDirectoryNavigation(linkList) s += showFileListing(self.data_listing(request, None)) s += showBlurb() s += showResourceStatistics(self.path, nodename) s += showHelpPreserve() s += showDisclaimer() s += "<hr/>" s += "<address>Angel/" + getVersionString( ) + " Server at " + nodename + "</address>" s += "</div>" s += "\n</body></html>" response = http.Response(200, {}, s) response.headers.setHeader("content-type", http_headers.MimeType('text', 'html')) return response
def renderDirectory(self, req): if req.method == 'HEAD': #no point in doing anything here in the angel context: used for exists() check only return http.Response(200, {}, "") if req.uri[-1] != "/": # Redirect to include trailing '/' in URI return http.RedirectResponse(req.unparseURL(path=req.path + '/')) # is there an index file? ifp = self.resource.fp.childSearchPreauth(*self.resource.indexNames) if ifp: # render from the index file return self.resource.createSimilarFile(ifp.path).render(req) # no index file, list the directory return DirectoryLister(self.resource.fp.path, self.resource.listChildren(), self.resource.contentTypes, self.resource.contentEncodings, self.resource.defaultType).render(req)
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
class Tile (resource.Resource) : def __init__ (self, images) : self.images = images def render (self, r) : f = r.args['f'][0] x = int(r.args['x'][0]) y = int(r.args['y'][0]) w = int(r.args['w'][0]) h = int(r.args['h'][0]) z = int(r.args['z'][0]) return self.images.getImage(f).getTile(x, y, w, h, z).addCallback(self._respond) def _respond (self, (ext, data)) : return http.Response( responsecode.OK, { 'Content-Type': http_headers.MimeType('image', ext) }, stream.MemoryStream(data) )
def _processingFailed(self, reason): # save the reason, it will be used for the stacktrace self._reason = reason exc = getattr(reason, 'value', None) if exc: # if the exception has 'http_error' and it is HTTPError, we use it to generate the response. # this allows us to attach http_error to non-HTTPError errors (as opposed to # re-raising HTTPError-derived exception) and enjoy the original stacktraces in the log if not isinstance(exc, http.HTTPError) and hasattr(exc, 'http_error'): http_error = exc.http_error if isinstance(http_error, http.HTTPError): return server.Request._processingFailed(self, failure.Failure(http_error)) elif isinstance(http_error, int): s = get_response_body(exc) response = http.Response(http_error, {'content-type': http_headers.MimeType('text','plain')}, stream=s) fail = failure.Failure(http.HTTPError(response)) return server.Request._processingFailed(self, fail) return server.Request._processingFailed(self, reason)
def render(self, req): contents = """<html> <head><title>Twisted.web2 demo server</title><head> <body> Hello! This is a twisted.web2 demo. <ul> <li><a href="file">Static File</a></li> <li><a href="dir/">Static dir listing</a></li> <li><a href="sleepy">Resource that takes time to render</a></li> <li><a href="wsgi">WSGI app</a></li> <li><a href="cgi">CGI app</a></li> <li><a href="forms">Forms</a></li> </ul> </body> </html>""" return http.Response( responsecode.OK, {'content-type': http_headers.MimeType('text', 'html')}, contents)
class LoginResource(resource.Resource): def render(self, ctx): late_import() try: username = ctx.args['username'][0] password = ctx.args['password'][0] U = notebook_twist.notebook.user(username) if not U.password_is(password): raise ValueError # want to return the same error message except KeyError, ValueError: return http.Response(stream="Invalid login.") worksheet = notebook_twist.notebook.create_new_worksheet( "_simple_session_", username, add_to_list=False) worksheet.sage() # create the sage session worksheet.initialize_sage() # is this a secure enough random number? session_id = "%x" % random.randint(1, 1 << 128) session = SessionObject(session_id, username, worksheet) sessions[session_id] = session status = session.get_status() return http.Response(stream="%s\n%s\n" % (simple_jsonize(status), SEP))
def renderHTTP(self, req): log.msg('Got request for %s from %s' % (req.uri, req.remoteAddr)) # Make sure the file is in the DB and unchanged if self.manager and not self.manager.db.isUnchanged(self.fp): if self.fp.exists() and self.fp.isfile(): self.fp.remove() return self._renderHTTP_done( http.Response( 404, {'content-type': http_headers.MimeType('text', 'html')}, '<html><body><p>File found but it has changed.</body></html>' ), req) resp = super(FileDownloader, self).renderHTTP(req) if isinstance(resp, defer.Deferred): resp.addCallbacks(self._renderHTTP_done, self._renderHTTP_error, callbackArgs=(req, ), errbackArgs=(req, )) else: resp = self._renderHTTP_done(resp, req) return resp
class FileUploader(static.File): """Modified to make it suitable for peer requests. Uses the modified L{Streams.FileUploadStream} to stream the file for throttling, and doesn't do any listing of directory contents. """ def render(self, req): if not self.fp.exists(): return responsecode.NOT_FOUND if self.fp.isdir(): # Don't try to render a directory listing return responsecode.NOT_FOUND 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() # Use the modified FileStream response.stream = FileUploadStream(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 testIfUnmodifiedSince(self): request = http.Request(None, "GET", "/", "HTTP/1.1", 0, http_headers.Headers()) out_headers = http_headers.Headers() response = http.Response(responsecode.OK, out_headers, None) # No Last-Modified => always fail. request.headers.setRawHeaders("If-Unmodified-Since", ('Mon, 03 Jan 2000 00:00:00 GMT', )) self.checkPreconditions(request, response, False, responsecode.PRECONDITION_FAILED) # Set output headers out_headers.setHeader("ETag", http_headers.ETag('foo')) out_headers.setHeader("Last-Modified", 946771200) # Sun, 02 Jan 2000 00:00:00 GMT request.headers.setRawHeaders("If-Unmodified-Since", ('Mon, 03 Jan 2000 00:00:00 GMT', )) self.checkPreconditions(request, response, True, responsecode.OK) request.headers.setRawHeaders("If-Unmodified-Since", ('Sat, 01 Jan 2000 00:00:00 GMT', )) self.checkPreconditions(request, response, False, responsecode.PRECONDITION_FAILED) # But if we have an error code already, ignore this header response.code = responsecode.INTERNAL_SERVER_ERROR self.checkPreconditions(request, response, True, responsecode.INTERNAL_SERVER_ERROR) response.code = responsecode.OK # invalid date => header ignored request.headers.setRawHeaders("If-Unmodified-Since", ('alalalalalalalalalala', )) self.checkPreconditions(request, response, True, responsecode.OK)
def sendResponse(self, response): if response.etag: self.e_tag = ETag(response.etag) response = http.Response(response.code, stream=response.data) return self.setHeaders(response)
def renderHTTP(self, request): application = getApplicationForURI(request.xcap_uri) if not application: return http.Response(responsecode.NOT_FOUND, stream="Application not supported") resource = self.resourceForURI(request.xcap_uri) return resource.renderHTTP(request)
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(self.responseCode, headers=self.responseHeaders, stream=self.responseStream())
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 render(self, req): return http.Response(responsecode.OK, http_headers.Headers( {'content-type': self.contentType()}), stream=self.data)
if fieldName in self.expectedFields: for finfo in req.files[fieldName]: try: outname = self.writeFile(*finfo) content.append("Saved file %s<br />" % outname) except IOError, err: content.append(str(err) + "<br />") else: content.append("%s is not a valid field" % fieldName) else: content.append("No files given") content.append("</body></html>") return http.Response(responsecode.OK, {}, stream='\n'.join(content)) # FIXME: hi there I am a broken class # """I contain AsIsProcessor, which serves files 'As Is' # Inspired by Apache's mod_asis # """ # # class ASISProcessor: # implements(iweb.IResource) # # def __init__(self, path): # self.path = path # # def renderHTTP(self, request): # request.startedWriting = 1
def render(self, req): return http.Response(200)
def sendFailureResponse(self, reason): response = http.Response(code=responsecode.BAD_GATEWAY, stream=str(reason.value)) self.deferred.callback(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 render(self, req): return http.Response(stream="Host:%s, Path:%s"%(req.host, req.path))
def renderHTTP(self, req): return http.Response(responsecode.NOT_FOUND)
def render(self, ctx): return http.Response(stream="Please login.")
def render(self, req): return http.Response(stream="prepath:%s postpath:%s" % ( req.prepath, req.postpath))
def render(self, ctx): return http.Response(responsecode.OK, {"content-type": self.content_type}, self.text)
def render(self, request): return http.Response(200, {'content-type': http_headers.MimeType( \ 'text', 'html')}, self.HTML) #'<html>empty</html>')
def _cbRender(self, result, request): s = dumps(result) return http.Response(responsecode.OK, {'content-type': http_headers.MimeType('text', 'json')}, s)
def render(self, ctx): return http.Response( 200, {'content-type': http_headers.MimeType('text', 'html')}, """<html><body> <a href="monkey">The source code of twisted.web2.static</a><br> <a href="elephant">A defined child</a></body></html>""")
def render(self, req): http.Response(200, stream='DEFAULT')