Python werkzeug.exceptions.MethodNotAllowed() Examples
The following are 30
code examples of werkzeug.exceptions.MethodNotAllowed().
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: 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 #2
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 #3
Source File: __init__.py From TagBot with MIT License | 5 votes |
def method_not_allowed(e: MethodNotAllowed) -> Union[HTML, JSON]: if request.is_json: resp: JSON = ({"error": "Method not allowed"}, 405) return resp return render_template("405.html"), 405
Example #4
Source File: exceptions.py From Flask with Apache License 2.0 | 5 votes |
def test_special_exceptions(self): exc = exceptions.MethodNotAllowed(['GET', 'HEAD', 'POST']) h = dict(exc.get_headers({})) self.assert_equal(h['Allow'], 'GET, HEAD, POST') self.assert_true('The method is not allowed' in exc.get_description())
Example #5
Source File: exceptions.py From Flask with Apache License 2.0 | 5 votes |
def test_aborter(self): abort = exceptions.abort self.assert_raises(exceptions.BadRequest, abort, 400) self.assert_raises(exceptions.Unauthorized, abort, 401) self.assert_raises(exceptions.Forbidden, abort, 403) self.assert_raises(exceptions.NotFound, abort, 404) self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) self.assert_raises(exceptions.NotAcceptable, abort, 406) self.assert_raises(exceptions.RequestTimeout, abort, 408) self.assert_raises(exceptions.Gone, abort, 410) self.assert_raises(exceptions.LengthRequired, abort, 411) self.assert_raises(exceptions.PreconditionFailed, abort, 412) self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413) self.assert_raises(exceptions.RequestURITooLarge, abort, 414) self.assert_raises(exceptions.UnsupportedMediaType, abort, 415) self.assert_raises(exceptions.UnprocessableEntity, abort, 422) self.assert_raises(exceptions.InternalServerError, abort, 500) self.assert_raises(exceptions.NotImplemented, abort, 501) self.assert_raises(exceptions.BadGateway, abort, 502) self.assert_raises(exceptions.ServiceUnavailable, abort, 503) myabort = exceptions.Aborter({1: exceptions.NotFound}) self.assert_raises(LookupError, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1) myabort = exceptions.Aborter(extra={1: exceptions.NotFound}) self.assert_raises(exceptions.NotFound, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1)
Example #6
Source File: routing.py From Flask with Apache License 2.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #7
Source File: exceptions.py From Flask with Apache License 2.0 | 5 votes |
def test_special_exceptions(self): exc = exceptions.MethodNotAllowed(['GET', 'HEAD', 'POST']) h = dict(exc.get_headers({})) self.assert_equal(h['Allow'], 'GET, HEAD, POST') self.assert_true('The method is not allowed' in exc.get_description())
Example #8
Source File: exceptions.py From Flask with Apache License 2.0 | 5 votes |
def test_aborter(self): abort = exceptions.abort self.assert_raises(exceptions.BadRequest, abort, 400) self.assert_raises(exceptions.Unauthorized, abort, 401) self.assert_raises(exceptions.Forbidden, abort, 403) self.assert_raises(exceptions.NotFound, abort, 404) self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) self.assert_raises(exceptions.NotAcceptable, abort, 406) self.assert_raises(exceptions.RequestTimeout, abort, 408) self.assert_raises(exceptions.Gone, abort, 410) self.assert_raises(exceptions.LengthRequired, abort, 411) self.assert_raises(exceptions.PreconditionFailed, abort, 412) self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413) self.assert_raises(exceptions.RequestURITooLarge, abort, 414) self.assert_raises(exceptions.UnsupportedMediaType, abort, 415) self.assert_raises(exceptions.UnprocessableEntity, abort, 422) self.assert_raises(exceptions.InternalServerError, abort, 500) self.assert_raises(exceptions.NotImplemented, abort, 501) self.assert_raises(exceptions.BadGateway, abort, 502) self.assert_raises(exceptions.ServiceUnavailable, abort, 503) myabort = exceptions.Aborter({1: exceptions.NotFound}) self.assert_raises(LookupError, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1) myabort = exceptions.Aborter(extra={1: exceptions.NotFound}) self.assert_raises(exceptions.NotFound, myabort, 404) self.assert_raises(exceptions.NotFound, myabort, 1)
Example #9
Source File: exceptions.py From ceph-lcm with Apache License 2.0 | 5 votes |
def get_headers(self, environ=None): headers = DecapodJSONMixin.get_headers(self, environ) headers.extend(exceptions.MethodNotAllowed.get_headers(self, environ)) return headers
Example #10
Source File: routing.py From data with GNU General Public License v3.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #11
Source File: routing.py From data with GNU General Public License v3.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #12
Source File: routing.py From data with GNU General Public License v3.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #13
Source File: routing.py From data with GNU General Public License v3.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #14
Source File: routing.py From data with GNU General Public License v3.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #15
Source File: routing.py From Werkzeug-docs-cn with BSD 2-Clause "Simplified" License | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #16
Source File: routing.py From appengine-try-python-flask with Apache License 2.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #17
Source File: views.py From py-flask-jsontools with BSD 2-Clause "Simplified" License | 5 votes |
def dispatch_request(self, *args, **kwargs): view = self._match_view(request.method, kwargs) if view is None: raise MethodNotAllowed(description='No view implemented for {}({})'.format(request.method, ', '.join(kwargs.keys()))) return view(*args, **kwargs)
Example #18
Source File: routing.py From arithmancer with Apache License 2.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #19
Source File: routing.py From cloud-playground with Apache License 2.0 | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #20
Source File: test_server.py From tfserve with MIT License | 5 votes |
def test_bad_requests(self): """Test unsupported HTTP methods. Anything but 'POST' should raise MethodNotAllowed. """ invalid_methods = ('GET', 'PUT', 'HEAD', 'FOOBAR') for method in invalid_methods: req = RequestProxy(method=method) with pytest.raises(MethodNotAllowed): self.server_A._handle_inference(req)
Example #21
Source File: tfserve.py From tfserve with MIT License | 5 votes |
def _handle_shutdown(req): """Handles shutown request. """ if req.method != 'POST': raise MethodNotAllowed(valid_methods=['POST']) shutdown = req.environ.get('werkzeug.server.shutdown') if not shutdown: raise BadRequest("server does not support shutdown") shutdown() return Response()
Example #22
Source File: tfserve.py From tfserve with MIT License | 5 votes |
def _handle_inference(self, req): """Handle inference request. """ if req.method != 'POST': raise MethodNotAllowed(valid_methods=['POST']) req_bytes = req.stream.read() try: resp_val = self._make_inference_impl(req_bytes) except BadInput as e: raise BadRequest(e.description) return Response(json.dumps(resp_val), content_type='application/json')
Example #23
Source File: routing.py From Flask-P2P with MIT License | 5 votes |
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method='--') except MethodNotAllowed as e: return e.valid_methods except HTTPException as e: pass return []
Example #24
Source File: common.py From cmdb with GNU General Public License v2.0 | 4 votes |
def urls(url, order): """Display all of the url matching routes for the project. Borrowed from Flask-Script, converted to use Click. """ rows = [] column_headers = ("Rule", "Endpoint", "Arguments") if url: try: rule, arguments = current_app.url_map.bind("localhost").match( url, return_rule=True ) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append(("<{}>".format(e), None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda x: getattr(x, order) ) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = "" table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += "{:" + str(max_rule_length) + "}" table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8 str_template += " {:" + str(max_endpoint_length) + "}" table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9 str_template += " {:" + str(max_arguments_length) + "}" table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo("-" * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))
Example #25
Source File: commands.py From flask-shop with BSD 3-Clause "New" or "Revised" License | 4 votes |
def urls(url, order): """Display all of the url matching routes for the project. Borrowed from Flask-Script, converted to use Click. """ rows = [] column_headers = ("Rule", "Endpoint", "Arguments") if url: try: rule, arguments = current_app.url_map.bind("localhost").match( url, return_rule=True ) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append((f"<{e}>", None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order) ) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = "" table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += "{:" + str(max_rule_length) + "}" table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) # max_endpoint_length = max(rows, key=len) max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8 str_template += " {:" + str(max_endpoint_length) + "}" table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9 str_template += " {:" + str(max_arguments_length) + "}" table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo("-" * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))
Example #26
Source File: skill_adapter.py From alexa-skills-kit-sdk-for-python with Apache License 2.0 | 4 votes |
def dispatch_request(self): # type: () -> Response """Method that handles request verification and routing. This method can be used as a function to register on the URL rule. The request is verified through the registered list of verifiers, before invoking the request handlers. The method returns a JSON response for the Alexa service to respond to the request. :return: The skill response for the input request :rtype: flask.Response :raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the method is invoked for other than HTTP POST request. :py:class:`werkzeug.exceptions.BadRequest` if the verification fails. :py:class:`werkzeug.exceptions.InternalServerError` for any internal exception. """ if flask_request.method != "POST": raise exceptions.MethodNotAllowed() if self._webservice_handler is None: raise AskSdkException("app not configured with skill handlers") try: content = flask_request.data.decode( verifier_constants.CHARACTER_ENCODING) response = self._webservice_handler.verify_request_and_dispatch( http_request_headers=typing.cast( typing.Dict[str, typing.Any], flask_request.headers), http_request_body=content) return jsonify(response) except VerificationException: current_app.logger.error( "Request verification failed", exc_info=True) raise exceptions.BadRequest( description="Incoming request failed verification") except AskSdkException: current_app.logger.error( "Skill dispatch exception", exc_info=True) raise exceptions.InternalServerError( description="Exception occurred during skill dispatch")
Example #27
Source File: commands.py From walle-web with Apache License 2.0 | 4 votes |
def urls(url, order): """Display all of the url matching routes for the project. Borrowed from Flask-Script, converted to use Click. """ rows = [] column_length = 0 column_headers = ('Rule', 'Endpoint', 'Arguments') if url: try: rule, arguments = ( current_app.url_map .bind('localhost') .match(url, return_rule=True)) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append(('<{}>'.format(e), None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order)) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = '' table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += '{:' + str(max_rule_length) + '}' table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) # max_endpoint_length = max(rows, key=len) max_endpoint_length = ( max_endpoint_length if max_endpoint_length > 8 else 8) str_template += ' {:' + str(max_endpoint_length) + '}' table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = ( max_arguments_length if max_arguments_length > 9 else 9) str_template += ' {:' + str(max_arguments_length) + '}' table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo('-' * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))
Example #28
Source File: commands.py From dribdat with MIT License | 4 votes |
def urls(url, order): """Display all of the url matching routes for the project. Borrowed from Flask-Script, converted to use Click. """ rows = [] column_length = 0 column_headers = ('Rule', 'Endpoint', 'Arguments') if url: try: rule, arguments = ( current_app.url_map .bind('localhost.localdomain') .match(url, return_rule=True)) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append(('<{}>'.format(e), None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order)) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = '' table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += '{:' + str(max_rule_length) + '}' table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) # max_endpoint_length = max(rows, key=len) max_endpoint_length = ( max_endpoint_length if max_endpoint_length > 8 else 8) str_template += ' {:' + str(max_endpoint_length) + '}' table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = ( max_arguments_length if max_arguments_length > 9 else 9) str_template += ' {:' + str(max_arguments_length) + '}' table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo('-' * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))
Example #29
Source File: commands.py From flask-realworld-example-app with MIT License | 4 votes |
def urls(url, order): """Display all of the url matching routes for the project. Borrowed from Flask-Script, converted to use Click. """ rows = [] column_headers = ('Rule', 'Endpoint', 'Arguments') if url: try: rule, arguments = ( current_app.url_map.bind('localhost') .match(url, return_rule=True)) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append(('<{}>'.format(e), None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order)) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = '' table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += '{:' + str(max_rule_length) + '}' table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) max_endpoint_length = ( max_endpoint_length if max_endpoint_length > 8 else 8) str_template += ' {:' + str(max_endpoint_length) + '}' table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = ( max_arguments_length if max_arguments_length > 9 else 9) str_template += ' {:' + str(max_arguments_length) + '}' table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo('-' * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))
Example #30
Source File: commands.py From MegaQC with GNU General Public License v3.0 | 4 votes |
def urls(url, order): """ Display all url routes. """ # Borrowed from Flask-Script, converted to use Click. rows = [] column_length = 0 column_headers = ("Rule", "Endpoint", "Arguments") if url: try: rule, arguments = current_app.url_map.bind("localhost").match( url, return_rule=True ) rows.append((rule.rule, rule.endpoint, arguments)) column_length = 3 except (NotFound, MethodNotAllowed) as e: rows.append(("<{}>".format(e), None, None)) column_length = 1 else: rules = sorted( current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order) ) for rule in rules: rows.append((rule.rule, rule.endpoint, None)) column_length = 2 str_template = "" table_width = 0 if column_length >= 1: max_rule_length = max(len(r[0]) for r in rows) max_rule_length = max_rule_length if max_rule_length > 4 else 4 str_template += "{:" + str(max_rule_length) + "}" table_width += max_rule_length if column_length >= 2: max_endpoint_length = max(len(str(r[1])) for r in rows) # max_endpoint_length = max(rows, key=len) max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8 str_template += " {:" + str(max_endpoint_length) + "}" table_width += 2 + max_endpoint_length if column_length >= 3: max_arguments_length = max(len(str(r[2])) for r in rows) max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9 str_template += " {:" + str(max_arguments_length) + "}" table_width += 2 + max_arguments_length click.echo(str_template.format(*column_headers[:column_length])) click.echo("-" * table_width) for row in rows: click.echo(str_template.format(*row[:column_length]))