def create_wikilink_response(self, res): if res is None: raise cherrpy.NotFound() wikientries = TagStore(res['tags']).get_wikipedia_tags() if not wikientries: raise cherrypy.NotFound() wikilink = 'https://%s.wikipedia.org/wiki/%s' for lang in cherrypy.request.locales: if lang in wikientries: title = urllib.parse.quote(wikientries[lang].replace(' ', '_')) raise cherrypy.HTTPRedirect(wikilink % (lang, title)) for k, v in wikientries.items(): url = "https://%s.wikipedia.org/w/api.php?action=query&prop=langlinks&titles=%s&llprop=url&&lllang=%s&format=json" % ( k, urllib.parse.quote(v.encode('utf8')), lang) try: req = urllib.request.Request( url, headers={'User-Agent': 'Python-urllib/2.7 Routemaps'}) data = urllib.request.urlopen(req).read().decode('utf-8') data = jsonlib.loads(data) except: continue # oh well, we tried (pgid, data) = data["query"]["pages"].popitem() if 'langlinks' in data: raise cherrypy.HTTPRedirect(data['langlinks'][0]['url']) else: # given up to find a requested language k, v = wikientries.popitem() raise cherrypy.HTTPRedirect( wikilink % (k, urllib.parse.quote(v.replace(' ', '_'))))
def render_prefs_panel(self, panelid, **kwargs): # @UnusedVariable # Process the parameters. params = dict() action = kwargs.get('action') if action: try: if action == "set_profile_info": params = self._handle_set_profile_info(**kwargs) elif action == "set_password": params = self._handle_set_password(**kwargs) elif action == "update_repos": params = self._handle_update_repos() else: _logger.info("unknown action: %s", action) raise cherrypy.NotFound("Unknown action") except RdiffWarning as e: params['warning'] = str(e) except RdiffError as e: params['error'] = str(e) except Exception as e: _logger.warning("unknown error processing action", exc_info=True) params['error'] = _("Unknown error") user = self.app.currentuser.username params.update({ 'email': self.app.currentuser.email, 'supports_set_email': self.app.userdb.supports('set_email', user), 'supports_set_password': self.app.userdb.supports('set_password', user), }) return "prefs_general.html", params
def _get(cls, pool_name, attrs=None, stats=False): # type: (str, str, bool) -> dict pools = cls._pool_list(attrs, stats) pool = [p for p in pools if p['pool_name'] == pool_name] if not pool: raise cherrypy.NotFound('No such pool') return pool[0]
def serve_file(self, flFile, user=None, content_type=None, publicShareId=None): """Set status, headers, and body in order to serve the given file. The Content-Type header will be set to the content_type arg, if provided. If not provided, the Content-Type will be guessed by the file extension of the 'path' argument. If disposition is not None, the Content-Disposition header will be set to "<disposition>; filename=<name>". If name is None, it will be set to the basename of path. If disposition is None, no Content-Disposition header will be written. """ config = cherrypy.request.app.config['filelocker'] cherrypy.response.headers['Pragma'] = "cache" cherrypy.response.headers['Cache-Control'] = "private" cherrypy.response.headers['Content-Length'] = flFile.size cherrypy.response.stream = True success, message = (True, "") if user is None: user = cherrypy.session.get("user") disposition = "attachment" path = os.path.join(config['vault'], str(flFile.id)) response = cherrypy.response try: st = os.stat(path) except OSError, ose: cherrypy.log.error("OSError while trying to serve file: %s" % str(ose)) raise cherrypy.NotFound()
def render_prefs_panel(self, panelid, **kwargs): # @UnusedVariable # Process the parameters. params = dict() action = kwargs.get('action') if action: try: if action == "set_notification_info": self._handle_set_notification_info(**kwargs) else: _logger.info("unknown action: %s", action) raise cherrypy.NotFound("Unknown action") except RdiffWarning as e: params['warning'] = str(e) except RdiffError as e: params['error'] = str(e) except Exception as e: _logger.warning("unknown error processing action", exc_info=True) params['error'] = _("Unknown error") params.update({ 'email': self.app.currentuser.email, 'repos': [ {'name': r.name, 'maxage': r.maxage} for r in self.app.currentuser.repo_list], }) return "prefs_notification.html", params
def get(self, svc_id): # type: (str) -> dict daemon = { 'rgw_metadata': [], 'rgw_id': svc_id, 'rgw_status': [] } service = CephService.get_service('rgw', svc_id) if not service: raise cherrypy.NotFound('Service rgw {} is not available'.format(svc_id)) metadata = service['metadata'] status = service['status'] if 'json' in status: try: status = json.loads(status['json']) except ValueError: logger.warning('%s had invalid status json', service['id']) status = {} else: logger.warning('%s has no key "json" in status', service['id']) daemon['rgw_metadata'] = metadata daemon['rgw_status'] = status return daemon
def GetFiles(self, args): searchPaths = [ 'wwwroot:/', 'script:/wwwroot/', 'script:/../../common/script/wwwroot/', 'script:/../../../carbon/common/script/wwwroot/', 'script:/../../../carbon/server/script/wwwroot/', 'script:/../../../eve/common/script/wwwroot/', 'script:/../../../eve/server/script/wwwroot/' ] files = [] filepath, filename = os.path.split(os.path.join(*args)) isSP = filename.lower().endswith('.py') for fn in ('app' + filename.capitalize(), filename): for path in searchPaths: rf = ResFile() fullPath = path + os.path.join(*(filepath, fn)).replace( '\\', '/') try: rf.OpenAlways(fullPath) files.append((fullPath, rf)) break except IOError: pass if files and not isSP: break if not files: raise cherrypy.NotFound() files.reverse() return (isSP, files)
def execution_traceback(self, id=None): if id == None: raise cherrypy.NotFound() else: ex = self.lims.fetch_execution(int(id)) template = self.lookup.get_template('execution_traceback.py') return template.render_unicode(id=int(id), ex_details=ex)
def elevation(self, oid, segments=None, **params): if segments is not None and segments.isdigit(): segments = int(segments) if segments > 500 or segments <= 0: segments = 500 else: segments = 100 w = cherrypy.request.app.config['DB']['map'].tables.ways.data gen = sa.select([sa.func.generate_series(0, segments).label('i') ]).alias() field = sa.func.ST_LineInterpolatePoint(w.c.geom, gen.c.i / float(segments)) field = sa.func.ST_Collect(field) sel = sa.select([field]).where(w.c.id == oid) res = cherrypy.request.db.execute(sel).first() if res is None or res[0] is None: raise cherrypy.NotFound() ret = OrderedDict() ret['id'] = oid compute_elevation(to_shape(res[0]), ret) return ret
def __call__(self, path_info): """Set handler and config for the current request.""" func = self.find_handler(path_info) if func: cherrypy.serving.request.handler = LateParamPageHandler(func) else: cherrypy.serving.request.handler = cherrypy.NotFound()
def view_class(self): view_class = self.context["publishable"].view_class if view_class is None: raise cherrypy.NotFound() return view_class
def page_template(self): template = self.context["publishable"].template if template is None: raise cherrypy.NotFound() return template
def __build_depot_http(self): """Build a DepotHTTP object to handle the current request.""" self.setup(cherrypy.request) headers = cherrypy.response.headers headers["Content-Type"] = "text/plain; charset=utf-8" toks = cherrypy.request.path_info.lstrip("/").split("/") repo_prefix = toks[0] if repo_prefix not in repositories: raise cherrypy.NotFound() repo = repositories[repo_prefix] depot_bui = depot_buis[repo_prefix] if repo_prefix in depot_https: return depot_https[repo_prefix] def request_pub_func(path_info): """A function that can be called to determine the publisher for a given request. We always want None here, to force DepotHTTP to fallback to the publisher information in the FMRI provided as part of the request, rather than the /publisher/ portion of path_info. """ return None depot_https[repo_prefix] = sd.DepotHTTP( repo, depot_bui.cfg, request_pub_func=request_pub_func) return depot_https[repo_prefix]
def file_detail(self, id=None): if id == None: raise cherrypy.NotFound() else: f = self.lims.fetch_file(int(id)) template = self.lookup.get_template('file_detail.py') return template.render_unicode(id=int(id), file_details=f)
def create_details_response(self, res): if res is None: raise cherrypy.NotFound() loctags = TagStore.make_localized(res['tags'], cherrypy.request.locales) cfg = cherrypy.request.app.config ret = api.common.RouteDict(res) ret['type'] = res['type'] if res.has_key('type') else 'relation' ret['symbol_url'] = '%s/symbols/%s/%s.svg' % ( cfg['Global']['MEDIA_URL'], cfg['Global']['BASENAME'], str(res['symbol'])) ret['mapped_length'] = int(res['length']) ret.add_if('official_length', loctags.get_length('distance', 'length', unit='m')) for tag in ('operator', 'note', 'description'): ret.add_if(tag, loctags.get(tag)) ret.add_if('url', loctags.get_url()) ret.add_if('wikipedia', loctags.get_wikipedia_tags()) ret['bbox'] = to_shape(res['bbox']).bounds if hasattr(self, '_hierarchy_list'): for name, val in (('subroutes', True), ('superroutes', False)): ret.add_if(name, self._hierarchy_list(ret['id'], val)) ret['tags'] = res['tags'] return ret
def execution_programs(self, id=None): if id == None: raise cherrypy.NotFound() else: ex = self.lims.fetch_execution(int(id)) template = self.lookup.get_template('execution_programs.py') return template.render_unicode(id=int(id), programs=ex['programs'])
def symbols(self, **params): from db.common.symbols import ShieldFactory factory = ShieldFactory( 'SwissMobile', 'JelRef', 'KCTRef', 'ItalianHikingRefs', 'OSMCSymbol', 'Nordic', 'Slopes', 'ShieldImage', 'TextColorBelow', 'ColorBox', 'TextSymbol', ) sym = factory.create(TagStore(params), params.get('_network', ''), 10) if sym is None: raise cherrypy.NotFound() with NamedTemporaryFile() as f: sym.write_image(f.name) factory._mangle_svg(f.name) with open(f.name, 'rb') as f: res = f.read() cherrypy.response.headers['Content-Type'] = 'image/svg+xml' return res
def comment(self, id, cancel=False, **data): link = self.data.get(id) if not link: raise cherrypy.NotFound() if cherrypy.request.method == 'POST': if cancel: raise cherrypy.HTTPRedirect('/info/%s' % link.id) form = CommentForm() try: data = form.to_python(data) markup = HTML(data['content']) | HTMLSanitizer() data['content'] = markup.render('xhtml') comment = link.add_comment(**data) if not ajax.is_xhr(): raise cherrypy.HTTPRedirect('/info/%s' % link.id) return template.render('_comment.html', comment=comment, num=len(link.comments)) except Invalid as e: errors = e.unpack_errors() else: errors = {} if ajax.is_xhr(): stream = template.render('_form.html', link=link, errors=errors) else: stream = template.render(link=link, comment=None, errors=errors) return stream | HTMLFormFiller(data=data)
def __call__(self, path_info): """Set handler and config for the current request.""" request = cherrypy.serving.request resource, vpath = self.find_handler(path_info) if resource: # Set Allow header avail = [m for m in dir(resource) if m.isupper()] if "GET" in avail and "HEAD" not in avail: avail.append("HEAD") avail.sort() cherrypy.serving.response.headers['Allow'] = ", ".join(avail) # Find the subhandler meth = request.method.upper() func = getattr(resource, meth, None) if func is None and meth == "HEAD": func = getattr(resource, "GET", None) if func: # Grab any _cp_config on the subhandler. if hasattr(func, "_cp_config"): request.config.update(func._cp_config) # Decode any leftover %2F in the virtual_path atoms. vpath = [x.replace("%2F", "/") for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.HTTPError(405) else: request.handler = cherrypy.NotFound()
def _cp_dispatch(self, vpath): # Only get here if vpath != None ent = cherrypy.request.remote.ip logger.info('ent:{}, vpath: {}'.format(ent, vpath)) if vpath[0] == 'static': return vpath if len(vpath) >= 2: ev = init_events(cherrypy.request.path_info, 'Test tool version:{}'.format(self.version)) oper_id = vpath.pop(0) test_id = vpath.pop(0) # verify test_id try: self.flows[test_id] except KeyError: raise cherrypy.HTTPError(400, 'Unknown TestID') if len(vpath): if len(vpath) == 1: endpoint = vpath.pop(0) op = self.op_handler.get(oper_id, test_id, ev, endpoint)[0] op.events.store(EV_ENDPOINT, endpoint) cherrypy.request.params['op'] = op if endpoint == 'registration': return self.registration elif endpoint == 'authorization': return self.authorization elif endpoint == 'token': return self.token elif endpoint == 'userinfo': return self.userinfo elif endpoint == 'claim': return self.claims elif endpoint == 'reset': return self.reset elif endpoint == 'end_session': return self.end_session elif endpoint == 'logout': return self.logout elif endpoint == 'check_session_iframe': return self.check_session_iframe elif endpoint == 'post_logout_page': return self.post_logout_page else: # Shouldn't be any other raise cherrypy.NotFound() if len(vpath) == 2: a = vpath.pop(0) b = vpath.pop(0) endpoint = '{}/{}'.format(a, b) if endpoint == ".well-known/openid-configuration": op = self.op_handler.get(oper_id, test_id, ev, endpoint)[0] cherrypy.request.params['op'] = op return self.configuration return self
def redirect_to_latest(self, ext): db = Db() latest = db.get_latest_by_extension(ext) if latest == (None, ): raise cherrypy.NotFound() else: raise cherrypy.HTTPRedirect(latest)
def __call__(self, path_info): request = cherrypy.serving.request func, vpath = self.find_handler(path_info) if func: vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.NotFound()
def default(self, id): try: kickstart = RenderedKickstart.by_id(id) except NoResultFound: raise cherrypy.NotFound(id) if kickstart.url: redirect(kickstart.url) return kickstart.kickstart.encode('utf8')
def newf(*args, **kwargs): username = getUsername() if username is None or username != service.secrets['onlineUser'][ 'user']: # 404 Not Found raise cherrypy.NotFound() return f(*args, **kwargs)
def serve(self, name): try: resource = self.resources[name] return serve_download(resource) except cherrypy.NotFound: raise except Exception: raise cherrypy.NotFound()
def GET(self, hotel_id=None): if hotel_id is None: return list(type(self).hotels.values()) try: return type(self).hotels[hotel_id] except KeyError: raise cherrypy.NotFound()
def __call__(self, id, processing, *args, **kwargs): # Get the requested element item = resolve_object_ref(Item, id) # Make sure the selected element exists if item is None: raise cherrypy.NotFound() # Normalize the URL to use a local id if id == item.global_id: raise cherrypy.HTTPRedirect(cherrypy.url().replace( "/" + id + "/", "/%d/" % item.id)) # Handle legacy image requests (woost < 0.8) if args or kwargs or "(" in processing: raise cherrypy.HTTPError(410) # Parse the given processing string, splitting the image factory from # the image format (ie. "home_thumbnail.png" -> ("home_thumbnail", "PNG")) parts = processing.rsplit(".", 1) parameters = None if len(parts) == 2: factory_id, ext = parts format = formats_by_extension.get(ext) if format is None: raise cherrypy.HTTPError(400, "Invalid image extension: %s" % ext) else: factory_id = processing format = None factory = ImageFactory.get_instance(identifier=factory_id) if factory is None: match = generic_image_factory_pattern.match(factory_id) if match: try: factory_id = int(match.group(1)) factory = ImageFactory.require_instance(factory_id) except: pass if factory is None: raise cherrypy.HTTPError( 400, "Invalid image factory id: %s" % factory_id) # Deny access to unauthorized elements get_current_user().require_permission(RenderPermission, target=item, image_factory=factory) try: image_cache_file = require_rendering(item, factory, format, parameters) except BadRenderingRequest, ex: raise cherrypy.HTTPError(400, ex.message)
def serve_file(path, content_type=None, disposition=None, name=None, debug=False): response = cherrypy.serving.response if not os.path.isabs(path): msg = "'%s' is not an absolute path." % path if debug: cherrypy.log(msg, 'TOOLS.STATICFILE') raise ValueError(msg) try: st = os.stat(path) except OSError: if debug: cherrypy.log('os.stat(%r) failed' % path, 'TOOLS.STATIC') raise cherrypy.NotFound() if stat.S_ISDIR(st.st_mode): if debug: cherrypy.log('%r is a directory' % path, 'TOOLS.STATIC') raise cherrypy.NotFound() response.headers['Last-Modified'] = httputil.HTTPDate(st.st_mtime) cptools.validate_since() if content_type is None: ext = '' i = path.rfind('.') if i != -1: ext = path[i:].lower() content_type = mimetypes.types_map.get(ext, None) if content_type is not None: response.headers['Content-Type'] = content_type if debug: cherrypy.log('Content-Type: %r' % content_type, 'TOOLS.STATIC') cd = None if disposition is not None: if name is None: name = os.path.basename(path) cd = '%s; filename="%s"' % (disposition, name) response.headers['Content-Disposition'] = cd if debug: cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC') content_length = st.st_size fileobj = open(path, 'rb') return _serve_fileobj(fileobj, content_type, content_length, debug=debug)
def _get(cls, pool_name: str, attrs: Optional[str] = None, stats: bool = False) -> dict: pools = cls._pool_list(attrs, stats) pool = [p for p in pools if p['pool_name'] == pool_name] if not pool: raise cherrypy.NotFound('No such pool') return pool[0]
def __handle_error(path, error): # All errors are treated as a 404 since reverse proxies such as Apache # don't handle 500 errors in a desirable way. For any error but a 404, # an error is logged. if error != http_client.NOT_FOUND: cherrypy.log("Error encountered while processing " "template: {0}\n".format(path), traceback=True) raise cherrypy.NotFound()