def getChild(self, name, request): """ Get the child page for the name given. This is called if our ancestors can't find our child. This is probably because the url is in unicode """ if name == '': return self else: name = unicode(name, 'utf8') result = self.children.get(name) if result is not None: return result else: session = request.getSession() if self.packagePath: session.packageStore.addPackage(self.package) self.bindNewPackage(self.package, session) self.packagePath = None if session.uid in self.mainpages.keys(): if name in self.mainpages[session.uid].keys(): return self.mainpages[session.uid][name] # This will just raise an error log.error("child %s not found. uri: %s" % (name, request.uri)) log.error("Session uid: %s, Mainpages: %s" % (session.uid, self.mainpages)) return error.NoResource( "No such child resource %(resource)s. Try again clicking %(link)s" % { "resource": name.encode('utf-8'), "link": "<a href='%s' target='_top'>%s</a>" % ('/', 'eXe') })
def getChildWithDefault(self, name, request): """Part of IResource, called by twisted.web to retrieve pages for URIs below this one. This just creates a Page instance for our StatsTarget's child, with a few special cases used for metadata and editing. """ childFactories = { '.message': MessageViewer.RootPage, '.rss': Feed.RSSFrontend, '.xml': Feed.XMLFeed, } if not name: # Ignore empty path sections return self elif name in childFactories: return childFactories[name](self) else: # Return the stats page for a child try: child = self.target.child(name) except ValueError: # Reserved word in stats target return error.NoResource("Invalid stats path") else: return self.__class__(self.component, child)
def getChild(self, name, txrequest): target = self.get_target() try: newtarget = getattr(target, name) return JsonRpcResource(newtarget) except AttributeError: return error.NoResource("No such child resource.")
def getChild(self, path, request): if path == "test": return test.TestResource() elif path == "monitor": return monitor.MonitorResource() else: return error.NoResource()
def render_GET(self, request): "Returns the keys for the bucket resource" "" LOG.debug(_("List keys for bucket %s"), self.name) try: bucket_object = bucket.Bucket(self.name) except exception.NotFound: return error.NoResource(message="No such bucket").render(request) if not bucket_object.is_authorized(request.context): LOG.audit(_("Unauthorized attempt to access bucket %s"), self.name, context=request.context) raise exception.NotAuthorized() prefix = get_argument(request, "prefix", u"") marker = get_argument(request, "marker", u"") max_keys = int(get_argument(request, "max-keys", 1000)) terse = int(get_argument(request, "terse", 0)) results = bucket_object.list_keys(prefix=prefix, marker=marker, max_keys=max_keys, terse=terse) render_xml(request, {"ListBucketResult": results}) return server.NOT_DONE_YET
def getWidget(self, name, request): """Get info for a particular participant. """ if name in self.service.participants.keys(): return ParticipantInfoWidget(name, self.service) else: return error.NoResource("That participant does not exist.")
def getChild(self, path, request): """Retrieve a 'child' resource from me. Implement this to create dynamic resource generation -- resources which are always available may be registered with self.putChild(). This will not be called if the class-level variable 'isLeaf' is set in your subclass; instead, the 'postpath' attribute of the request will be left as a list of the remaining path elements. For example, the URL /foo/bar/baz will normally be:: | site.resource.getChild('foo').getChild('bar').getChild('baz'). However, if the resource returned by 'bar' has isLeaf set to true, then the getChild call will never be made on it. @param path: a string, describing the child @param request: a twisted.web.server.Request specifying meta-information about the request that is being made for this child. """ # This is ugly, I know, but since error.py directly accesses # resource.Resource during import-time (it subclasses it), the Resource # class must be defined by the time error is imported. from twisted.web import error return error.NoResource("No such child resource.")
def _do_render(res): path = '/'.join(request.postpath) if path in self._registered_resources: content, content_type = self._registered_resources[path][1] if content is None or content_type is None: e = error.NoResource("Resource not configured.") request.write(e.render(request)) else: request.setHeader('content-type', str(content_type)) request.setHeader('content-length', str(len(content))) if type(content) == unicode: content = content.encode('utf-8') request.write(content) else: e = error.NoResource("Resource not found.").render(request) request.write(e) request.finish()
def broken_render(self, result, request): log.msg("callback broke!, with result:'%s', request: '%s' " % (result, request)) e = error.NoResource('not there').render(request) request.setResponseCode(404) request.write(e) request.finish() return result
def render_POST(self, request): path = request.path[len(self.prefix):] if path[0] == "/": handler = self.COMMANDS.get(path[1:]) if handler is not None: return handler(self, request) raise PassthruException, http_error.NoResource().render(request)
def getChild(self, path, request): if path == 'static': return self.static_files if path not in self.connections: if 'htmlfile' in request.path: return transports.htmlfile.CloseResource(); return error.NoResource("<script>alert('whoops');</script>") # print 'returning self.connections[%s]' % (path,) return self.connections[path]
def getChildWithDefault(self, name, request): if not name: # Ignore empty path sections return self else: try: return MessagePage(self.statsPage, int(name, 16)) except ValueError: return error.NoResource("Message ID is invalid")
def render(self, request): xml = self.target.messages.getMessageById(self.id) if xml: request.setHeader('content-type', 'text/xml') request.write(unicode(XML.toString(xml)).encode('utf-8')) request.finish() else: request.write(error.NoResource("Message not found").render(request)) request.finish() return ""
def getChild(self, path, request): """See twisted.web.Resource.getChild. The point of this is to temporarily ignore the non-existance of media files, because they are likely to be in production. 404s are generated eventually. Uses a dictionary to remember recent requests """ try: the_path = self.children[path] return self.children[path] except KeyError: return error.NoResource('not there')
def render_HEAD(self, request): filename = request.path[1:] # Remove the leading / if self.files.has_key(filename): file = self.files[filename] request.setHeader("Content-Length", str(file.legacyftp.filesize)) request.setHeader( "Content-Disposition", "attachment; filename=\"%s\"" % file.legacyftp.filename.encode("utf-8")) return "" else: page = error.NoResource(message="404 File Not Found") return page.render(request)
def getLocale(self, request): """ Request a localization and respond with json object of appropriate locale """ requested = request.args.get("locale") #?locale=fr setLocales = request.getCookie( "locale") #preferred locale (todo implement)? locales = [] if requested: locales = requested elif setLocales: locales = json.loads(setLocales) else: lang_header = request.headers.get( "Accept-Language", "en") # for example en-US,en;q=0.8,es;q=0.6 locales = [ locale.split(';')[0] for locale in lang_header.split(',') ] basePath = self.localePath + (request.args.get("path", [""])[0]) if not basePath.endswith("/"): basePath += "/" if not os.path.exists(basePath): raise http_error.NoResource().render(request) lang = getJSON(basePath + "base.json") # reverse so specificity overrides for locale in reversed(locales): path = basePath + locale + ".json" if os.path.exists(path): lang.update(getJSON(path)) cache(request) # apply_gzip(request) request.write(json.dumps(lang)) request.finish() return True
def render(self, request): return error.NoResource("There's no index here, you need a message ID").render(request)
def noResource(self, *args): return error.NoResource(*args)
class DbResource(AdamoResource): isLeaf = True def __init__(self, parent, db, staticDirs, **kw): self.db = db ## self.staticDirs = {} ## for (alias,path) in staticDirs.items(): ## fr = static.File(path) ## print alias,"=", fr ## self.staticDirs[alias] = fr AdamoResource.__init__(self, parent, **kw) #self._window = TwistedWindow(ctx) #ctx._db.schema.defineMenus(ctx,self._window) #def getChild(self, name, request): # raise "should never be called since isLeaf is True" def getSession(self, request): sess = AdamoResource.getSession(self, request) sess.use(db=self.db) return sess def findTarget(self, request): pp = list(request.postpath) if len(pp) and len(pp[-1]) == 0: pp = pp[:-1] if len(pp) == 0: return self.db.getContentRoot() cmd = pp[0] if cmd == "db": del pp[0] ds = self.db.getDatasource(pp[0]) if len(pp) == 1: return ds del pp[0] #pp = pp[1:] id = pp[0].split(',') pka = ds._table.getPrimaryAtoms() if len(id) != len(pka): raise InvalidRequestError('invalid id "%s"' % pp[0]) rid = [] i = 0 for (name, type) in pka: try: v = type.parse(id[i]) except ValueError, e: msg = "'%s' is not an %s" % (repr(id[i]), repr(type)) raise InvalidRequestError(msg) rid.append(v) i += 1 row = ds.peek(*rid) if row is None: msg = "%s(%s) : no such row" % (ds._table.getTableName(), repr(id)) raise InvalidRequestError(msg) return row if cmd == "menu": #return self.respond(request,self._window) #return self._window.getRenderer(request) raise "und jetzt?" #return self._window ## try: ## #print request.method ## fr = self.staticDirs[cmd] ## del request.postpath[0] ## return fr.render(request) ## except KeyError,e: ## print str(e) return error.NoResource('invalid postpath: %s' % str(pp)).render(request)
class File(resource.Resource, styles.Versioned, filepath.FilePath): """ 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 . @cvar childNotFound: L{Resource} used to render 404 Not Found error pages. """ contentTypes = loadMimeTypes() contentEncodings = {".gz": "gzip", ".bz2": "bzip2"} processors = {} indexNames = ["index", "index.html", "index.htm", "index.trp", "index.rpy"] type = None ### Versioning persistenceVersion = 6 def upgradeToVersion6(self): self.ignoredExts = [] if self.allowExt: self.ignoreExt("*") del self.allowExt def upgradeToVersion5(self): if not isinstance(self.registry, Registry): self.registry = Registry() def upgradeToVersion4(self): if not hasattr(self, 'registry'): self.registry = {} def upgradeToVersion3(self): if not hasattr(self, 'allowExt'): self.allowExt = 0 def upgradeToVersion2(self): self.defaultType = "text/html" def upgradeToVersion1(self): if hasattr(self, 'indexName'): self.indexNames = [self.indexName] del self.indexName def __init__(self, path, defaultType="text/html", ignoredExts=(), registry=None, allowExt=0): """Create a file with the given path. """ resource.Resource.__init__(self) filepath.FilePath.__init__(self, path) # Remove the dots from the path to split self.defaultType = defaultType if ignoredExts in (0, 1) or allowExt: warnings.warn("ignoredExts should receive a list, not a boolean") if ignoredExts or allowExt: self.ignoredExts = ['*'] else: self.ignoredExts = [] else: self.ignoredExts = list(ignoredExts) self.registry = registry or Registry() def ignoreExt(self, ext): """Ignore the given extension. Serve file.ext if file is requested """ self.ignoredExts.append(ext) childNotFound = error.NoResource("File not found.") def directoryListing(self): from twisted.web.woven import dirlist return dirlist.DirectoryLister(self.path, self.listNames(), self.contentTypes, self.contentEncodings, self.defaultType) def getChild(self, path, request): """See twisted.web.Resource.getChild. """ self.restat() if not self.isdir(): return self.childNotFound if path: fpath = self.child(path) else: fpath = self.childSearchPreauth(*self.indexNames) if fpath is None: return self.directoryListing() if not fpath.exists(): fpath = fpath.siblingExtensionSearch(*self.ignoredExts) if fpath is None: return self.childNotFound if platformType == "win32": # don't want .RPY to be different than .rpy, since that would allow # source disclosure. processor = InsensitiveDict(self.processors).get( fpath.splitext()[1]) else: processor = self.processors.get(fpath.splitext()[1]) if processor: return resource.IResource(processor(fpath.path, self.registry)) return self.createSimilarFile(fpath.path) # methods to allow subclasses to e.g. decrypt files on the fly: def openForReading(self): """Open a file and return it.""" return self.open() def getFileSize(self): """Return file size.""" return self.getsize() def render(self, request): """You know what you doing.""" self.restat() if self.type is None: self.type, self.encoding = getTypeAndEncoding( self.basename(), self.contentTypes, self.contentEncodings, self.defaultType) if not self.exists(): return self.childNotFound.render(request) if self.isdir(): return self.redirect(request) #for content-length fsize = size = self.getFileSize() # request.setHeader('accept-ranges','bytes') if self.type: request.setHeader('content-type', self.type) if self.encoding: request.setHeader('content-encoding', self.encoding) try: f = self.openForReading() except IOError, e: import errno if e[0] == errno.EACCES: return error.ForbiddenResource().render(request) else: raise if request.setLastModified(self.getmtime()) is http.CACHED: return '' # Commented out because it's totally broken. --jknight 11/29/04 # try: # range = request.getHeader('range') # # if range is not None: # # This is a request for partial data... # bytesrange = string.split(range, '=') # assert bytesrange[0] == 'bytes',\ # "Syntactically invalid http range header!" # start, end = string.split(bytesrange[1],'-') # if start: # f.seek(int(start)) # if end: # end = int(end) # size = end # else: # end = size # request.setResponseCode(http.PARTIAL_CONTENT) # request.setHeader('content-range',"bytes %s-%s/%s " % ( # str(start), str(end), str(size))) # #content-length should be the actual size of the stuff we're # #sending, not the full size of the on-server entity. # fsize = end - int(start) # # request.setHeader('content-length', str(fsize)) # except: # traceback.print_exc(file=log.logfile) request.setHeader('content-length', str(fsize)) if request.method == 'HEAD': return '' # return data FileTransfer(f, size, request) # and make sure the connection doesn't get closed return server.NOT_DONE_YET
class File(resource.Resource, styles.Versioned, filepath.FilePath): """ 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 . @cvar childNotFound: L{Resource} used to render 404 Not Found error pages. """ contentTypes = loadMimeTypes() contentEncodings = {".gz": "gzip", ".bz2": "bzip2"} processors = {} indexNames = ["index", "index.html", "index.htm", "index.trp", "index.rpy"] type = None ### Versioning persistenceVersion = 6 def upgradeToVersion6(self): self.ignoredExts = [] if self.allowExt: self.ignoreExt("*") del self.allowExt def upgradeToVersion5(self): if not isinstance(self.registry, Registry): self.registry = Registry() def upgradeToVersion4(self): if not hasattr(self, 'registry'): self.registry = {} def upgradeToVersion3(self): if not hasattr(self, 'allowExt'): self.allowExt = 0 def upgradeToVersion2(self): self.defaultType = "text/html" def upgradeToVersion1(self): if hasattr(self, 'indexName'): self.indexNames = [self.indexName] del self.indexName def __init__(self, path, defaultType="text/html", ignoredExts=(), registry=None, allowExt=0): """Create a file with the given path. """ resource.Resource.__init__(self) filepath.FilePath.__init__(self, path) # Remove the dots from the path to split self.defaultType = defaultType if ignoredExts in (0, 1) or allowExt: warnings.warn("ignoredExts should receive a list, not a boolean") if ignoredExts or allowExt: self.ignoredExts = ['*'] else: self.ignoredExts = [] else: self.ignoredExts = list(ignoredExts) self.registry = registry or Registry() def ignoreExt(self, ext): """Ignore the given extension. Serve file.ext if file is requested """ self.ignoredExts.append(ext) childNotFound = error.NoResource("File not found.") def directoryListing(self): return DirectoryLister(self.path, self.listNames(), self.contentTypes, self.contentEncodings, self.defaultType) def getChild(self, path, request): """See twisted.web.Resource.getChild. """ self.restat() if not self.isdir(): return self.childNotFound if path: fpath = self.child(path) else: fpath = self.childSearchPreauth(*self.indexNames) if fpath is None: return self.directoryListing() if not fpath.exists(): fpath = fpath.siblingExtensionSearch(*self.ignoredExts) if fpath is None: return self.childNotFound if platformType == "win32": # don't want .RPY to be different than .rpy, since that would allow # source disclosure. processor = InsensitiveDict(self.processors).get( fpath.splitext()[1]) else: processor = self.processors.get(fpath.splitext()[1]) if processor: return resource.IResource(processor(fpath.path, self.registry)) return self.createSimilarFile(fpath.path) # methods to allow subclasses to e.g. decrypt files on the fly: def openForReading(self): """Open a file and return it.""" return self.open() def getFileSize(self): """Return file size.""" return self.getsize() def _parseRangeHeader(self, range): """ Return a two-tuple of the start and stop value from the given range header. Raise ValueError if the header is syntactically invalid or if the Bytes-Unit is anything other than "bytes". """ try: kind, value = range.split('=', 1) except ValueError: raise ValueError("Missing '=' separator") kind = kind.strip() if kind != 'bytes': raise ValueError("Unsupported Bytes-Unit: %r" % (kind, )) byteRanges = filter(None, map(str.strip, value.split(','))) if len(byteRanges) > 1: # Support for multiple ranges should be added later. For now, this # implementation gives up. raise ValueError("Multiple Byte-Ranges not supported") firstRange = byteRanges[0] try: start, end = firstRange.split('-', 1) except ValueError: raise ValueError("Invalid Byte-Range: %r" % (firstRange, )) if start: try: start = int(start) except ValueError: raise ValueError("Invalid Byte-Range: %r" % (firstRange, )) else: start = None if end: try: end = int(end) except ValueError: raise ValueError("Invalid Byte-Range: %r" % (firstRange, )) else: end = None if start is not None: if end is not None and start > end: # Start must be less than or equal to end or it is invalid. raise ValueError("Invalid Byte-Range: %r" % (firstRange, )) elif end is None: # One or both of start and end must be specified. Omitting both is # invalid. raise ValueError("Invalid Byte-Range: %r" % (firstRange, )) return start, end def _doRangeRequest(self, request, (start, end)): """ Responds to simple Range-Header requests. Simple means that only the first byte range is handled. @raise ValueError: If the given Byte-Ranges-Specifier was invalid @return: A three-tuple of the start, length, and end byte of the response. """ size = self.getFileSize() if start is None: # Omitted start means that the end value is actually a start value # relative to the end of the resource. start = size - end end = size elif end is None: # Omitted end means the end of the resource should be the end of # the range. end = size elif end < size: # If the end was specified (this is an else for `end is None`) and # there's room, bump the value by one to compensate for the # disagreement between Python and the HTTP RFC on whether the # closing index of the range is inclusive (HTTP) or exclusive # (Python). end += 1 if start >= size: # This range doesn't overlap with any of this resource, so the # request is unsatisfiable. request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE) request.setHeader('content-range', 'bytes */%d' % (size, )) start = end = 0 else: request.setResponseCode(http.PARTIAL_CONTENT) request.setHeader('content-range', 'bytes %d-%d/%d' % (start, end - 1, size)) return start, (end - start), end
# Sibling Imports from twisted.web import server from twisted.web import error from twisted.web import resource from twisted.web.util import redirectTo # Twisted Imports from twisted.web import http from twisted.python import threadable, log, components, failure, filepath from twisted.internet import abstract, interfaces, defer from twisted.spread import pb from twisted.persisted import styles from twisted.python.util import InsensitiveDict from twisted.python.runtime import platformType dangerousPathError = error.NoResource("Invalid request URL.") def isDangerous(path): return path == '..' or '/' in path or os.sep in path class Data(resource.Resource): """ This is a static, in-memory resource. """ def __init__(self, data, type): resource.Resource.__init__(self) self.data = data self.type = type
def getChild(self, path, request): if path in transports.map: return transports.create(path, self) return error.NoResource("No such child resource.")
def getChild(self, path, request): if path.startswith('stomp'): return StompDispatcherResource() else: return error.NoResource()
def getChild(self, name, request): if name: return TacSlaveResource(name) else: return error.NoResource()
def getChild(self, name, request): """ Get the child page for the name given. This is called if our ancestors can't find our child. This is probably because the url is in unicode """ if name == '': return self elif name == 'gdrive-callback': gdrive_callback = ''' <html> <head> <title>Export Package to Google Drive</title> <script type="text/javascript"> function getAuthResult() { var authResult = {}; var paramsString = window.location.hash.substring(1); var paramsArray = paramsString.split('&'); for (var i = 0; i < paramsArray.length; i++) { var kvp = paramsArray[i].split('='); console.log(kvp); // Check multiple values value = decodeURIComponent(kvp[1]).split('+'); if (value.length == 1) { value = value[0]; } key = decodeURIComponent(kvp[0]); authResult[key] = value; } return authResult; } authResult = getAuthResult(); opener.eXe.controller.Toolbar.prototype.processExportGoogleDrive(authResult); window.close(); </script> </head> <body> <h1>Export Package to Google Drive</h1> </body> </html>''' return gdrive_callback else: name = unicode(name, 'utf8') result = self.children.get(name) if result is not None: return result else: session = request.getSession() if self.packagePath: session.packageStore.addPackage(self.package) self.bindNewPackage(self.package, session) self.packagePath = None if session.uid in self.mainpages.keys(): if name in self.mainpages[session.uid].keys(): return self.mainpages[session.uid][name] # This will just raise an error log.error("child %s not found. uri: %s" % (name, request.uri)) log.error("Session uid: %s, Mainpages: %s" % (session.uid, self.mainpages)) return error.NoResource( "No such child resource %(resource)s. Try again clicking %(link)s" % { "resource": name.encode('utf-8'), "link": "<a href='%s'>%s</a>" % ('/', 'eXe') })
def getChild(self, path, request): return error.NoResource("No such child resource.")