Python werkzeug.exceptions.NotFound() Examples
The following are 30
code examples of werkzeug.exceptions.NotFound().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
werkzeug.exceptions
, or try the search function
.
Example #1
Source File: helpers.py From Flask-P2P with MIT License | 6 votes |
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path would fall out of `directory`. """ filename = posixpath.normpath(filename) for sep in _os_alt_seps: if sep in filename: raise NotFound() if os.path.isabs(filename) or \ filename == '..' or \ filename.startswith('../'): raise NotFound() return os.path.join(directory, filename)
Example #2
Source File: helpers.py From jbox with MIT License | 6 votes |
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path would fall out of `directory`. """ filename = posixpath.normpath(filename) for sep in _os_alt_seps: if sep in filename: raise NotFound() if os.path.isabs(filename) or \ filename == '..' or \ filename.startswith('../'): raise NotFound() return os.path.join(directory, filename)
Example #3
Source File: helpers.py From api-pycon2014 with MIT License | 6 votes |
def match_url(url, method=None): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match a URL without the ' 'application context being pushed. This has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create a URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not '' and \ parsed_url.netloc != url_adapter.server_name: raise NotFound() return url_adapter.match(parsed_url.path, method)
Example #4
Source File: urls.py From flask-react-spa with MIT License | 6 votes |
def url(url, method): """Show details for a specific URL.""" from werkzeug.exceptions import MethodNotAllowed, NotFound try: rule, arguments = current_app.url_map.bind('localhost')\ .match(url, method=method, return_rule=True) _print_url_rules( ('Rule', 'Endpoint', 'View', 'Arguments', 'Options'), [(rule.rule, rule.endpoint, _get_rule_view(rule), _format_dict(arguments), _format_rule_options(rule), )] ) except (NotFound, MethodNotAllowed) as e: _print_url_rules(('Rule',), [(f'<{e}>',)])
Example #5
Source File: helpers.py From cloud-playground with Apache License 2.0 | 6 votes |
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path would fall out of `directory`. """ filename = posixpath.normpath(filename) for sep in _os_alt_seps: if sep in filename: raise NotFound() if os.path.isabs(filename) or \ filename == '..' or \ filename.startswith('../'): raise NotFound() return os.path.join(directory, filename)
Example #6
Source File: test_decorators.py From flask-react-spa with MIT License | 6 votes |
def test_404_on_lookup_error(self, models): from backend.security.models import User, Role @param_converter(id=User, role_id=Role) def method(user, role): assert False with pytest.raises(NotFound): method(id=0, role_id=models.ROLE_USER.id) @param_converter(id=User, role_id=Role) def method(user, role): assert False with pytest.raises(NotFound): method(id=models.user.id, role_id=0)
Example #7
Source File: utils.py From gordo with GNU Affero General Public License v3.0 | 6 votes |
def metadata_required(f): """ Decorate a view which has ``gordo_name`` as a url parameter and will set ``g.metadata`` to that model's metadata """ @wraps(f) def wrapper(*args: tuple, gordo_project: str, gordo_name: str, **kwargs: dict): try: g.metadata = load_metadata(directory=g.collection_dir, name=gordo_name) except FileNotFoundError: raise NotFound(f"No model found for '{gordo_name}'") else: return f(*args, **kwargs) return wrapper
Example #8
Source File: utils.py From gordo with GNU Affero General Public License v3.0 | 6 votes |
def model_required(f): """ Decorate a view which has ``gordo_name`` as a url parameter and will set ``g.model`` to be the loaded model and ``g.metadata`` to that model's metadata """ @wraps(f) def wrapper(*args: tuple, gordo_project: str, gordo_name: str, **kwargs: dict): try: g.model = load_model(directory=g.collection_dir, name=gordo_name) except FileNotFoundError: raise NotFound(f"No such model found: '{gordo_name}'") else: # If the model was required, the metadata is also required. return metadata_required(f)( *args, gordo_project=gordo_project, gordo_name=gordo_name, **kwargs ) return wrapper
Example #9
Source File: index.py From listenbrainz-server with GNU General Public License v2.0 | 6 votes |
def mb_user_deleter(musicbrainz_row_id): """ This endpoint is used by MusicBrainz to delete accounts once they are deleted on MusicBrainz too. See https://tickets.metabrainz.org/browse/MBS-9680 for details. Args: musicbrainz_row_id (int): the MusicBrainz row ID of the user to be deleted. Returns: 200 if the user has been successfully found and deleted from LB Raises: NotFound if the user is not found in the LB database Unauthorized if the MusicBrainz access token provided with the query is invalid """ _authorize_mb_user_deleter(request.args.get('access_token', '')) user = db_user.get_by_mb_row_id(musicbrainz_row_id) if user is None: raise NotFound('Could not find user with MusicBrainz Row ID: %d' % musicbrainz_row_id) delete_user(user['musicbrainz_id']) return jsonify({'status': 'ok'}), 200
Example #10
Source File: delete.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def post(self, name): if not may(DELETE): raise Forbidden() try: with current_app.storage.open(name) as item: if not item.meta[COMPLETE] and not may(ADMIN): error = 'Upload incomplete. Try again later.' return render_template('error.html', heading=item.meta[FILENAME], body=error), 409 if item.meta[LOCKED] and not may(ADMIN): raise Forbidden() current_app.storage.remove(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise return redirect_next_referrer('bepasty.index')
Example #11
Source File: setkv.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def post(self, name): if self.REQUIRED_PERMISSION is not None and not may(self.REQUIRED_PERMISSION): raise Forbidden() try: with current_app.storage.openwrite(name) as item: if item.meta[self.KEY] == self.NEXT_VALUE: error = '%s already is %r.' % (self.KEY, self.NEXT_VALUE) elif not item.meta[COMPLETE]: error = 'Upload incomplete. Try again later.' else: error = None if error: return render_template('error.html', heading=item.meta[FILENAME], body=error), 409 item.meta[self.KEY] = self.NEXT_VALUE return redirect_next_referrer('bepasty.display', name=name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise
Example #12
Source File: upload.py From bepasty-server with BSD 2-Clause "Simplified" License | 6 votes |
def get(self, name): if not may(CREATE): raise Forbidden() try: item = current_app.storage.open(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: return 'No file found.', 404 raise if item.meta[COMPLETE]: error = 'Upload complete. Cannot delete fileupload garbage.' else: error = None if error: return error, 409 try: item = current_app.storage.remove(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise return 'Upload aborted'
Example #13
Source File: user.py From listenbrainz-server with GNU General Public License v2.0 | 6 votes |
def delete_user(musicbrainz_id): """ Delete a user from ListenBrainz completely. First, drops the user's influx measurement and then deletes the user from the database. Args: musicbrainz_id (str): the MusicBrainz ID of the user Raises: NotFound if user isn't present in the database """ user = _get_user(musicbrainz_id) _influx.delete(user.musicbrainz_id) publish_data_to_queue( data={ 'type': 'delete.user', 'musicbrainz_id': musicbrainz_id, }, exchange=current_app.config['BIGQUERY_EXCHANGE'], queue=current_app.config['BIGQUERY_QUEUE'], error_msg='Could not put user %s into queue for deletion, please try again later' % musicbrainz_id, ) db_user.delete(user.id)
Example #14
Source File: web_app.py From testplan with Apache License 2.0 | 6 votes |
def get(self, report_uid): """Get a Testplan report (JSON) given it's uid.""" # report_uid will be used when looking up the report from a database. report_path = os.path.abspath( os.path.join( app.config["DATA_PATH"], app.config["TESTPLAN_REPORT_NAME"] ) ) if os.path.exists(report_path): return send_from_directory( directory=os.path.dirname(report_path), filename=os.path.basename(report_path), ) else: raise exceptions.NotFound()
Example #15
Source File: view.py From flask-resty with MIT License | 6 votes |
def get_item_or_404(self, id, **kwargs): """Get an item by ID; raise a 404 if it not found. This will get an item by ID per `get_item` below. If no item is found, it will rethrow the `NoResultFound` exception as an HTTP 404. :param id: The item ID. :return: The item corresponding to the ID. :rtype: object """ try: item = self.get_item(id, **kwargs) except NoResultFound as e: raise NotFound() from e return item
Example #16
Source File: __init__.py From veripress with MIT License | 6 votes |
def send_static_file(self, filename): """ Send static files from the static folder in the current selected theme prior to the global static folder. :param filename: static filename :return: response object """ if self.config['MODE'] == 'api-only': # if 'api-only' mode is set, we should not send static files abort(404) theme_static_folder = getattr(self, 'theme_static_folder', None) if theme_static_folder: try: return send_from_directory(theme_static_folder, filename) except NotFound: pass return super(CustomFlask, self).send_static_file(filename)
Example #17
Source File: user.py From listenbrainz-server with GNU General Public License v2.0 | 6 votes |
def delete_listens_history(musicbrainz_id): """ Delete a user's listens from ListenBrainz completely. This, drops the user's influx measurement and resets their listen count. Args: musicbrainz_id (str): the MusicBrainz ID of the user Raises: NotFound if user isn't present in the database """ user = _get_user(musicbrainz_id) _influx.delete(user.musicbrainz_id) _influx.reset_listen_count(user.musicbrainz_id) db_user.reset_latest_import(user.musicbrainz_id) db_stats.delete_user_stats(user.id)
Example #18
Source File: app_test.py From pysheeet with MIT License | 6 votes |
def test_acme(self): """Test that send a request for a acme key.""" token = self.token key = self.key self.assertEqual(acme(token), key) token = token + "_env" key = key + "_env" os.environ["ACME_TOKEN_ENV"] = token os.environ["ACME_KEY_ENV"] = key self.assertEqual(find_key(token), key) del os.environ["ACME_TOKEN_ENV"] del os.environ["ACME_KEY_ENV"] self.assertRaises(NotFound, acme, token)
Example #19
Source File: urls.py From flask-unchained with MIT License | 6 votes |
def url(url: str, method: str): """Show details for a specific URL.""" try: url_rule, params = (current_app.url_map.bind('localhost') .match(url, method=method, return_rule=True)) except (NotFound, MethodNotAllowed) as e: click.secho(str(e), fg='white', bg='red') else: headings = ('Method(s)', 'Rule', 'Params', 'Endpoint', 'View', 'Options') print_table(headings, [(_get_http_methods(url_rule), url_rule.rule if url_rule.strict_slashes else url_rule.rule + '[/]', _format_dict(params), url_rule.endpoint, _get_rule_view(url_rule), _format_rule_options(url_rule))], ['<' if i > 0 else '>' for i, col in enumerate(headings)], primary_column_idx=1)
Example #20
Source File: test_app_cache.py From veripress with MIT License | 6 votes |
def test_app(): # app's config should be loaded from instance/config.py assert app.config['STORAGE_TYPE'] == 'file' assert app.config['THEME'] == 'test' with app.test_request_context('/'): app.send_static_file('no-use.css') app.send_static_file('no-use-2.css') with raises(NotFound): app.send_static_file('non-exists.css') origin_mode = app.config['MODE'] app.config['MODE'] = 'api-only' with app.test_request_context('/'): with raises(NotFound): app.send_static_file('no-use.css') app.config['MODE'] = origin_mode
Example #21
Source File: test_decorators.py From flask-unchained with MIT License | 6 votes |
def test_404_on_lookup_error(self, user, role): from ._bundles.vendor_one.models import OneUser, OneRole @param_converter(id=OneUser, one_role_id=OneRole) def method(one_user, one_role): assert False with pytest.raises(NotFound): method(id=0, one_role_id=role.id) @param_converter(id=OneUser, one_role_id=OneRole) def method(one_user, one_role): assert False with pytest.raises(NotFound): method(id=user.id, one_role_id=0)
Example #22
Source File: helpers.py From Financial-Portfolio-Flask with MIT License | 6 votes |
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path would fall out of `directory`. """ filename = posixpath.normpath(filename) for sep in _os_alt_seps: if sep in filename: raise NotFound() if os.path.isabs(filename) or \ filename == '..' or \ filename.startswith('../'): raise NotFound() return os.path.join(directory, filename)
Example #23
Source File: helpers.py From Flask-P2P with MIT License | 5 votes |
def send_from_directory(directory, filename, **options): """Send a file from a given directory with :func:`send_file`. This is a secure way to quickly expose static files from an upload folder or something similar. Example usage:: @app.route('/uploads/<path:filename>') def download_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True) .. admonition:: Sending files and Performance It is strongly recommended to activate either `X-Sendfile` support in your webserver or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance. .. versionadded:: 0.5 :param directory: the directory where all the files are stored. :param filename: the filename relative to that directory to download. :param options: optional keyword arguments that are directly forwarded to :func:`send_file`. """ filename = safe_join(directory, filename) if not os.path.isfile(filename): raise NotFound() options.setdefault('conditional', True) return send_file(filename, **options)
Example #24
Source File: blueprints.py From syntheticmass with Apache License 2.0 | 5 votes |
def test_safe_access(self): app = moduleapp with app.test_request_context(): f = app.view_functions['admin.static'] try: f('/etc/passwd') except NotFound: pass else: self.assert_true(0, 'expected exception') try: f('../__init__.py') except NotFound: pass else: self.assert_true(0, 'expected exception') # testcase for a security issue that may exist on windows systems import os import ntpath old_path = os.path os.path = ntpath try: try: f('..\\__init__.py') except NotFound: pass else: self.assert_true(0, 'expected exception') finally: os.path = old_path
Example #25
Source File: helpers.py From gae-angular-material-starter with MIT License | 5 votes |
def make_not_found_exception(): """Raises 404 Not Found exception Raises: HTTPException: with 404 code """ raise exceptions.NotFound()
Example #26
Source File: webserver.py From nichtparasoup with MIT License | 5 votes |
def on_get(self, _: Request) -> Union[_SimpleJsonResponse, NotFound]: response = self.imageserver.get_image() return _SimpleJsonResponse({ 'uri': response.image.uri, 'is_generic': response.image.is_generic, 'source': response.image.source, 'more': response.image.more, 'crawler': { 'id': id(response.crawler), 'type': _type_module_name_str(type(response.crawler.imagecrawler)), }, }) if response else NotFound()
Example #27
Source File: webserver.py From nichtparasoup with MIT License | 5 votes |
def on_status_what(self, _: Request, what: str) -> Union[NotFound, _SimpleJsonResponse]: status_type = self._STATUS_WHATS.get(what) return _SimpleJsonResponse(status_type(self.imageserver)) if status_type else NotFound()
Example #28
Source File: utils.py From oreilly-flask-apis-video with MIT License | 5 votes |
def split_url(url, method='GET'): """Returns the endpoint name and arguments that match a given URL. In other words, this is the reverse of Flask's url_for().""" appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to match a URL without the ' 'application context being pushed. This has to be ' 'executed when application context is available.') if reqctx is not None: url_adapter = reqctx.url_adapter else: url_adapter = appctx.url_adapter if url_adapter is None: raise RuntimeError('Application was not able to create a URL ' 'adapter for request independent URL matching. ' 'You might be able to fix this by setting ' 'the SERVER_NAME config variable.') parsed_url = url_parse(url) if parsed_url.netloc is not '' and \ parsed_url.netloc != url_adapter.server_name: raise ValidationError('Invalid URL: ' + url) try: result = url_adapter.match(parsed_url.path, method) except NotFound: raise ValidationError('Invalid URL: ' + url) return result
Example #29
Source File: profile.py From listenbrainz-server with GNU General Public License v2.0 | 5 votes |
def import_data(): """ Displays the import page to user, giving various options """ # Return error if LASTFM_API_KEY is not given in config.py if 'LASTFM_API_KEY' not in current_app.config or current_app.config['LASTFM_API_KEY'] == "": return NotFound("LASTFM_API_KEY not specified.") user_data = { "id": current_user.id, "name": current_user.musicbrainz_id, "auth_token": current_user.auth_token, } props = { "user": user_data, "profile_url": url_for('user.profile', user_name=user_data["name"]), "api_url": current_app.config["API_URL"], "lastfm_api_url": current_app.config["LASTFM_API_URL"], "lastfm_api_key": current_app.config["LASTFM_API_KEY"], } return render_template( "user/import.html", user=current_user, props=ujson.dumps(props), )
Example #30
Source File: app.py From rapidbay with MIT License | 5 votes |
def frontend(path): try: return send_from_directory("/app/frontend/", path) except NotFound: pass return send_from_directory("/app/frontend/", "index.html")