def http_get_item_version_by_id(self, request): query = ( request.dbsession.query(ItemVersion) .filter_by(id=int(request.GET["version_id"])) .limit(1)) if query.count() == 0: from paste.httpexceptions import HTTPNotFound raise HTTPNotFound() return request.respond(json.dumps(self.item_to_json(query.first())), mimetype="text/plain")
def __call__(self, environ, start_response): path = [part for part in environ.get('PATH_INFO', '').split('/') if part] if len(path) > 2: raise ValueError, "too many components in url" if len(path) > 0 and path[-1] == 'index.html': path.pop() path_len = len(path) if path_len == 0: filename = self.checkBaseIndex() elif path_len == 1: if path[0] == "favicon.ico": return HTTPNotFound()(environ, start_response) filename = self.checkPackageIndex(path[0]) else: filename = self.checkEggFor(path[0], path[1]) if filename is None: return HTTPNotFound()(environ, start_response) return FileApp(filename)(environ, start_response)
def _get_handler(self, environ): path = environ['PATH_INFO'] filepath = p.join(self._basedir, *path.split('/')) if not p.exists(filepath): return HTTPNotFound('The resource does not exist', comment="Nothing at %r" % path).wsgi_application # TODO: this exposes all files; sep. query-views-tplts and static files if p.isfile(filepath): return FileApp(filepath) else: data, mimetype, encoding = self._process_view(filepath) headers = [ ('Content-Type', mimetype), ('Content-Encoding', encoding), ] return DataApp(data, headers)
def __call__(self, environ, start_response): path_info = environ['PATH_INFO'] #log.debug ('static search for %s' % path_info) if path_info in self.files: path, app = self.files.get(path_info) if not app: app = FileApp (path).cache_control (max_age=60*60*24*7*6) #6 weeks self.files[path_info] = (path, app) log.info ( "STATIC REQ %s" % path_info) if_none_match = environ.get('HTTP_IF_NONE_MATCH') if if_none_match: mytime = os.stat(path).st_mtime if str(mytime) == if_none_match: headers = [] ETAG.update(headers, mytime) start_response('304 Not Modified', headers) return [''] # empty body else: app = HTTPNotFound(comment=path_info) return app(environ, start_response)
def default(self, trans, target1=None, target2=None, **kwd): """ Called on any url that does not match a controller method. """ raise HTTPNotFound( 'This link may not be followed from within Galaxy.' )
def get_values(self, path, kwargs, headers): history = self._history branch = history._branch revid = self.get_revid() file_id = kwargs.get('file_id', None) if file_id is not None: file_id = urlutils.unquote_to_bytes(osutils.safe_utf8(file_id)) if (file_id is None) and (path is None): raise HTTPBadRequest('No file_id or filename ' 'provided to view') try: if file_id is None: file_id = history.get_file_id(revid, path) if path is None: path = history.get_path(revid, file_id) except (NoSuchId, NoSuchRevision): raise HTTPNotFound() filename = os.path.basename(path) change = history.get_changes([revid])[0] # If we're looking at the tip, use head: in the URL instead if revid == branch.last_revision(): revno_url = 'head:' else: revno_url = history.get_revno(revid) # Directory Breadcrumbs directory_breadcrumbs = ( util.directory_breadcrumbs( self._branch.friendly_name, self._branch.is_root, 'files')) tree = history.revision_tree(revid) # Create breadcrumb trail for the path within the branch branch_breadcrumbs = util.branch_breadcrumbs(path, tree, 'files') try: if tree.kind(path) == "directory": raise HTTPMovedPermanently( self._branch.context_url(['/files', revno_url, path])) except NoSuchFile: raise HTTPNotFound() # no navbar for revisions navigation = util.Container() return { # In AnnotateUI, "annotated" is a dictionary mapping lines to # changes. We exploit the fact that bool({}) is False when # checking whether we're in "annotated" mode. 'annotated': {}, 'revno_url': revno_url, 'file_id': file_id, 'file_path': path, 'filename': filename, 'navigation': navigation, 'change': change, 'contents': self.file_contents(path, revid), 'fileview_active': True, 'directory_breadcrumbs': directory_breadcrumbs, 'branch_breadcrumbs': branch_breadcrumbs, }
def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO', '') environ['file_root'] = self.root environ['login_url'] = self.login_url environ['home_url'] = self.home_url environ['record_info_uri'] = self.record_info_uri environ['saml_trusted_ca_dir'] = self.saml_trusted_ca_dir environ['authz_service_uri'] = self.authz_service_uri environ['attr_service_uri'] = self.attr_service_uri environ.setdefault('pydap.renderer', self.renderer) is_directory = False filepath = os.path.abspath( os.path.normpath( os.path.join(self.root, path_info.lstrip('/').replace('/', os.path.sep)))) basename, extension = os.path.splitext(filepath) assert filepath.startswith(self.root) # check for ".." exploit # check whether the path ends with a slash if path_info.endswith(os.path.sep): # check for regular file or dir request if os.path.exists(filepath): # it is actually a file if os.path.isfile(filepath): return HTTPNotFound()(environ, start_response) # it is a directory else: is_directory = True # Check if the filepath is a path in the archive if self._is_data_path(filepath): form = parse_formvars(environ) if is_directory: if len(form) > 0: glob = form.get('glob', '') depth = int(form.get('depth', '1')) try: multi_file_view = MultiFileView( environ, start_response, filepath, glob, depth) action = form.get('action', '') if action.lower() == 'download': # Download mutiple files. return multi_file_view.download_files() else: # Preview mutiple files for download. return multi_file_view.list_files() except ValueError as e: logger.error( ("An exception has occurred parsing " "multiple files for {0}: {1}".format(filepath, e))) else: if 'plot' in form: file_plot_view = FilePlotView(environ, start_response, filepath, form) if form.get('plot') == 'img': # Generate a plot image from the file. return file_plot_view.generate() else: # Load a form for plotting a file. return file_plot_view.form() # No specific action taken. # Log access. logger.info( format_access_message(environ, is_directory=is_directory)) # Check if the filepath without its extension is a path in the archive elif self._is_data_path(basename): # File could be being handled by a handler. handler = get_handler(basename, self.handlers) # Log access. logger.info(format_access_message(environ, extension, handler)) return super(CEDAFileServer, self).__call__(environ, start_response)
def __call__(self, environ, start_response): request_is_private = (environ['SERVER_PORT'] == str( config.codebrowse.private_port)) environ['loggerhead.static.url'] = environ['SCRIPT_NAME'] if environ['PATH_INFO'].startswith('/static/'): path_info_pop(environ) return static_app(environ, start_response) elif environ['PATH_INFO'] == '/favicon.ico': return favicon_app(environ, start_response) elif environ['PATH_INFO'] == '/robots.txt': return robots_app(environ, start_response) elif not request_is_private: if environ['PATH_INFO'].startswith('/+login'): return self._complete_login(environ, start_response) elif environ['PATH_INFO'].startswith('/+logout'): return self._logout(environ, start_response) path = environ['PATH_INFO'] trailingSlashCount = len(path) - len(path.rstrip('/')) if request_is_private: # Requests on the private port are internal API requests from # something that has already performed security checks. As # such, they get read-only access to everything. identity_url = LAUNCHPAD_SERVICES user = LAUNCHPAD_SERVICES else: identity_url = environ[self.session_var].get( 'identity_url', LAUNCHPAD_ANONYMOUS) user = environ[self.session_var].get('user', LAUNCHPAD_ANONYMOUS) lp_server = get_lp_server(identity_url, branch_transport=self.get_transport()) lp_server.start_server() try: try: branchfs = self.get_branchfs() transport_type, info, trail = branchfs.translatePath( identity_url, urlutils.escape(path)) except xmlrpclib.Fault as f: if check_fault(f, faults.PathTranslationError): raise HTTPNotFound() elif check_fault(f, faults.PermissionDenied): # If we're not allowed to see the branch... if environ['wsgi.url_scheme'] != 'https': # ... the request shouldn't have come in over http, as # requests for private branches over http should be # redirected to https by the dynamic rewrite script we # use (which runs before this code is reached), but # just in case... env_copy = environ.copy() env_copy['wsgi.url_scheme'] = 'https' raise HTTPMovedPermanently(construct_url(env_copy)) elif user != LAUNCHPAD_ANONYMOUS: # ... if the user is already logged in and still can't # see the branch, they lose. exc = HTTPUnauthorized() exc.explanation = "You are logged in as %s." % user raise exc else: # ... otherwise, lets give them a chance to log in # with OpenID. return self._begin_login(environ, start_response) else: raise if transport_type != BRANCH_TRANSPORT: raise HTTPNotFound() trail = urlutils.unescape(trail).encode('utf-8') trail += trailingSlashCount * '/' amount_consumed = len(path) - len(trail) consumed = path[:amount_consumed] branch_name = consumed.strip('/') self.log.info('Using branch: %s', branch_name) if trail and not trail.startswith('/'): trail = '/' + trail environ['PATH_INFO'] = trail environ['SCRIPT_NAME'] += consumed.rstrip('/') branch_url = lp_server.get_url() + branch_name branch_link = urlparse.urljoin(config.codebrowse.launchpad_root, branch_name) cachepath = os.path.join(config.codebrowse.cachepath, branch_name[1:]) if not os.path.isdir(cachepath): os.makedirs(cachepath) self.log.info('branch_url: %s', branch_url) private = info['private'] if private: self.log.info("Branch is private") else: self.log.info("Branch is public") try: bzr_branch = safe_open(lp_server.get_url().strip(':/'), branch_url) except errors.NotBranchError as err: self.log.warning('Not a branch: %s', err) raise HTTPNotFound() bzr_branch.lock_read() try: view = BranchWSGIApp(bzr_branch, branch_name, {'cachepath': cachepath}, self.graph_cache, branch_link=branch_link, served_url=None, private=private) return view.app(environ, start_response) finally: bzr_branch.repository.revisions.clear_cache() bzr_branch.repository.signatures.clear_cache() bzr_branch.repository.inventories.clear_cache() if bzr_branch.repository.chk_bytes is not None: bzr_branch.repository.chk_bytes.clear_cache() bzr_branch.repository.texts.clear_cache() bzr_branch.unlock() finally: lp_server.stop_server()
def render( self, trans, visualization_name, visualization=None, config=None, embedded=None, **kwargs ): """ Render the appropriate visualization template, parsing the `kwargs` into appropriate variables and resources (such as ORM models) based on this visualizations `param` data in visualizations_conf.xml. URL: /visualization/show/{visualization_name} """ config = config or {} # validate name vs. registry registry = trans.app.visualizations_registry if not registry: raise HTTPNotFound( 'No visualization registry (possibly disabled in galaxy.ini)' ) if visualization_name not in registry.plugins: raise HTTPNotFound( 'Unknown or invalid visualization: ' + visualization_name ) plugin = registry.plugins[ visualization_name ] returned = None try: # get the config for passing to the template from the kwargs dict, parsed using the plugin's params setting config_from_kwargs = registry.query_dict_to_config( trans, self, visualization_name, kwargs ) config.update( config_from_kwargs ) config = OpenObject( **config ) # further parse config to resources (models, etc.) used in template based on registry config resources = registry.query_dict_to_resources( trans, self, visualization_name, config ) # if a saved visualization, pass in the encoded visualization id or None if a new render encoded_visualization_id = None if visualization: encoded_visualization_id = trans.security.encode_id( visualization.id ) visualization_display_name = plugin.config[ 'name' ] title = visualization.latest_revision.title if visualization else kwargs.get( 'title', None ) # look up template and render template_path = plugin.config[ 'template' ] returned = registry.fill_template( trans, plugin, template_path, visualization_name=visualization_name, visualization_display_name=visualization_display_name, title=title, saved_visualization=visualization, visualization_id=encoded_visualization_id, embedded=embedded, #NOTE: passing *unparsed* kwargs as query query=kwargs, #NOTE: vars is a dictionary for shared data in the template # this feels hacky to me but it's what mako recommends: # http://docs.makotemplates.org/en/latest/runtime.html vars={}, config=config, **resources ) except Exception, exception: log.exception( 'error rendering visualization (%s): %s', visualization_name, str( exception ) ) if trans.debug: raise returned = trans.show_error_message( "There was an error rendering the visualization. " + "Contact your Galaxy administrator if the problem persists." + "<br/>Details: " + str( exception ), use_panels=False )