Skip to content
Myr

Merge pull request #5063 from pallets/cli-routes-domain

Before adoption: this commit came in with the history the project adopted, so no landing records it.

show subdomain or host in routes output

authored by David Lord · committed by GitHub · parents 182ce3d, 84c007d · Browse files · 3 files+69 added−49 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+69 added−49 removed

  • tests:+28 added−23 removed
  • other:+41 added−26 removed

3 files+69 added−49 removed

modified:src/flask/cli.py+39 added-26 removed
7 unmodified lines
8import sys9import traceback10import typing as t11from functools import update_wrapper12from operator import attrgetter12from operator import itemgetter1314import click15from click.core import ParameterSource16from werkzeug import run_simple
971 unmodified lines
988@click.command("routes", short_help="Show the routes for the app.")989@click.option(990 "--sort",991 "-s",992 type=click.Choice(("endpoint", "methods", "rule", "match")),992 type=click.Choice(("endpoint", "methods", "domain", "rule", "match")),993 default="endpoint",994 help=(995 'Method to sort routes by. "match" is the order that Flask will match '996 "routes when dispatching a request."995 "Method to sort routes by. 'match' is the order that Flask will match routes"996 " when dispatching a request."997 ),998)999@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")1000@with_appcontext1001def routes_command(sort: str, all_methods: bool) -> None:1002 """Show all registered routes with endpoints and methods."""10031003 rules = list(current_app.url_map.iter_rules())10041005 if not rules:1006 click.echo("No routes were registered.")1007 return10081009 ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))1009 ignored_methods = set() if all_methods else {"HEAD", "OPTIONS"}1010 host_matching = current_app.url_map.host_matching1011 has_domain = any(rule.host if host_matching else rule.subdomain for rule in rules)1012 rows = []10131011 if sort in ("endpoint", "rule"):1012 rules = sorted(rules, key=attrgetter(sort))1013 elif sort == "methods":1014 rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore1014 for rule in rules:1015 row = [1016 rule.endpoint,1017 ", ".join(sorted((rule.methods or set()) - ignored_methods)),1018 ]10191016 rule_methods = [1017 ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore1018 for rule in rules1019 ]1020 if has_domain:1021 row.append((rule.host if host_matching else rule.subdomain) or "")10221021 headers = ("Endpoint", "Methods", "Rule")1022 widths = (1023 max(len(rule.endpoint) for rule in rules),1024 max(len(methods) for methods in rule_methods),1025 max(len(rule.rule) for rule in rules),1026 )1027 widths = [max(len(h), w) for h, w in zip(headers, widths)]1028 row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)1023 row.append(rule.rule)1024 rows.append(row)10251030 click.echo(row.format(*headers).strip())1031 click.echo(row.format(*("-" * width for width in widths)))1026 headers = ["Endpoint", "Methods"]1027 sorts = ["endpoint", "methods"]10281033 for rule, methods in zip(rules, rule_methods):1034 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())1029 if has_domain:1030 headers.append("Host" if host_matching else "Subdomain")1031 sorts.append("domain")10321033 headers.append("Rule")1034 sorts.append("rule")10351036 try:1037 rows.sort(key=itemgetter(sorts.index(sort)))1038 except ValueError:1039 pass10401041 rows.insert(0, headers)1042 widths = [max(len(row[i]) for row in rows) for i in range(len(headers))]1043 rows.insert(1, ["-" * w for w in widths])1044 template = " ".join(f"{{{i}:<{w}}}" for i, w in enumerate(widths))10451046 for row in rows:1047 click.echo(template.format(*row))104810491050cli = FlaskGroup(1051 name="flask",1052 help="""\1053A general utility script for Flask applications.
14 unmodified lines
modified:tests/test_cli.py+28 added-23 removed
431 unmodified lines
432class TestRoutes:433 @pytest.fixture434 def app(self):435 app = Flask(__name__)436 app.testing = True437438 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])439 def yyy_get_post(x, y):440 pass441442 @app.route("/zzz_post", methods=["POST"])443 def aaa_post():444 pass445436 app.add_url_rule(437 "/get_post/<int:x>/<int:y>",438 methods=["GET", "POST"],439 endpoint="yyy_get_post",440 )441 app.add_url_rule("/zzz_post", methods=["POST"], endpoint="aaa_post")442 return app443444 @pytest.fixture445 def invoke(self, app, runner):446 cli = FlaskGroup(create_app=lambda: app)447 return partial(runner.invoke, cli)448453 @pytest.fixture454 def invoke_no_routes(self, runner):455 def create_app():456 app = Flask(__name__, static_folder=None)457 app.testing = True458459 return app460461 cli = FlaskGroup(create_app=create_app)462 return partial(runner.invoke, cli)463449 def expect_order(self, order, output):450 # skip the header and match the start of each row451 for expect, line in zip(order, output.splitlines()[2:]):452 # do this instead of startswith for nicer pytest output
24 unmodified lines
477 assert "GET, HEAD, OPTIONS, POST" not in output478 output = invoke(["routes", "--all-methods"]).output479 assert "GET, HEAD, OPTIONS, POST" in output480496 def test_no_routes(self, invoke_no_routes):497 result = invoke_no_routes(["routes"])481 def test_no_routes(self, runner):482 app = Flask(__name__, static_folder=None)483 cli = FlaskGroup(create_app=lambda: app)484 result = runner.invoke(cli, ["routes"])485 assert result.exit_code == 0486 assert "No routes were registered." in result.output487488 def test_subdomain(self, runner):489 app = Flask(__name__, static_folder=None)490 app.add_url_rule("/a", subdomain="a", endpoint="a")491 app.add_url_rule("/b", subdomain="b", endpoint="b")492 cli = FlaskGroup(create_app=lambda: app)493 result = runner.invoke(cli, ["routes"])494 assert result.exit_code == 0495 assert "Subdomain" in result.output496497 def test_host(self, runner):498 app = Flask(__name__, static_folder=None, host_matching=True)499 app.add_url_rule("/a", host="a", endpoint="a")500 app.add_url_rule("/b", host="b", endpoint="b")501 cli = FlaskGroup(create_app=lambda: app)502 result = runner.invoke(cli, ["routes"])503 assert result.exit_code == 0504 assert "Host" in result.output505506507def dotenv_not_available():508 try:509 import dotenv # noqa: F401510 except ImportError:
173 unmodified lines
modified:CHANGES.rst+2 added
42 unmodified lines
43- ``SESSION_COOKIE_DOMAIN`` does not fall back to ``SERVER_NAME``. The default is not44 to set the domain, which modern browsers interpret as an exact match rather than45 a subdomain match. Warnings about ``localhost`` and IP addresses are also removed.46 :issue:`5051`47- The ``routes`` command shows each rule's ``subdomain`` or ``host`` when domain48 matching is in use. :issue:`5004`495051Version 2.2.452-------------
1423 unmodified lines