show subdomain or host in routes output
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 182ce3d · 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
Provenance
- Commit
84c007d- Tree
db764e5- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
182ce3d
3 files changed+69 added−49 removed
modified:src/flask/cli.py+39 added-26 removed
7 unmodified lines8 import sys9 import traceback10 import typing as t11 from functools import update_wrapper12-from operator import attrgetter12+from operator import itemgetter13 14 import click15 from click.core import ParameterSource16 from werkzeug import run_simple971 unmodified lines988 @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_appcontext1001 def routes_command(sort: str, all_methods: bool) -> None:1002 """Show all registered routes with endpoints and methods."""1003-1003 rules = list(current_app.url_map.iter_rules())1004+1005 if not rules:1006 click.echo("No routes were registered.")1007 return1008 1009- 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 = []1013 1011- 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+ ]1019 1016- 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 "")1022 1021- 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)1025 1030- click.echo(row.format(*headers).strip())1031- click.echo(row.format(*("-" * width for width in widths)))1026+ headers = ["Endpoint", "Methods"]1027+ sorts = ["endpoint", "methods"]1028 1033- 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")1032 1033+ headers.append("Rule")1034+ sorts.append("rule")1035 1036+ try:1037+ rows.sort(key=itemgetter(sorts.index(sort)))1038+ except ValueError:1039+ pass1040+1041+ 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))1045+1046+ for row in rows:1047+ click.echo(template.format(*row))1048+1049+1050 cli = FlaskGroup(1051 name="flask",1052 help="""\1053 A general utility script for Flask applications.14 unmodified linesmodified:tests/test_cli.py+28 added-23 removed
431 unmodified lines432 class TestRoutes:433 @pytest.fixture434 def app(self):435 app = Flask(__name__)436- app.testing = True437-438- @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])439- def yyy_get_post(x, y):440- pass441-442- @app.route("/zzz_post", methods=["POST"])443- def aaa_post():444- pass445-436+ 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 app443 444 @pytest.fixture445 def invoke(self, app, runner):446 cli = FlaskGroup(create_app=lambda: app)447 return partial(runner.invoke, cli)448 453- @pytest.fixture454- def invoke_no_routes(self, runner):455- def create_app():456- app = Flask(__name__, static_folder=None)457- app.testing = True458-459- return app460-461- cli = FlaskGroup(create_app=create_app)462- return partial(runner.invoke, cli)463-449 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 output24 unmodified lines477 assert "GET, HEAD, OPTIONS, POST" not in output478 output = invoke(["routes", "--all-methods"]).output479 assert "GET, HEAD, OPTIONS, POST" in output480 496- 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.output487 488+ 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.output496 497+ 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.output505+506+507 def dotenv_not_available():508 try:509 import dotenv # noqa: F401510 except ImportError:173 unmodified linesmodified:CHANGES.rst+2 added
42 unmodified lines43 - ``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`49 50 51 Version 2.2.452 -------------1423 unmodified lines