Merge pull request #2259 from davidism/routes-command
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add routes command
authored by David Lord · committed by GitHub · parents 71b7c4f, 7ad7958 · Browse files · 3 files·+125 added−11 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+125 added−11 removed
- tests:+69 added−9 removed
- other:+56 added−2 removed
Provenance
- Commit
39d5552- Tree
e32bca1- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
71b7c4f- Parent 2
7ad7958
3 files changed+125 added−11 removed
modified:flask/cli.py+53 added-2 removed
10 unmodified lines11 12 import os13 import sys14 import traceback15-from threading import Lock, Thread15 from functools import update_wrapper16+from operator import attrgetter17+from threading import Lock, Thread18 19 import click20 21+from . import __version__22 from ._compat import iteritems, reraise23+from .globals import current_app24 from .helpers import get_debug_flag22-from . import __version__25 26+27 class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""29 30 290 unmodified lines321 322 if add_default_commands:323 self.add_command(run_command)324 self.add_command(shell_command)325+ self.add_command(routes_command)326 327 self._loaded_plugin_commands = False328 329 def _load_plugin_commands(self):157 unmodified lines487 488 code.interact(banner=banner, local=ctx)489 490 491+@click.command('routes', short_help='Show the routes for the app.')492+@click.option(493+ '--sort', '-s',494+ type=click.Choice(('endpoint', 'methods', 'rule', 'match')),495+ default='endpoint',496+ help=(497+ 'Method to sort routes by. "match" is the order that Flask will match '498+ 'routes when dispatching a request.'499+ )500+)501+@click.option(502+ '--all-methods',503+ is_flag=True,504+ help="Show HEAD and OPTIONS methods."505+)506+@with_appcontext507+def routes_command(sort, all_methods):508+ """Show all registered routes with endpoints and methods."""509+510+ rules = list(current_app.url_map.iter_rules())511+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512+513+ if sort in ('endpoint', 'rule'):514+ rules = sorted(rules, key=attrgetter(sort))515+ elif sort == 'methods':516+ rules = sorted(rules, key=lambda rule: sorted(rule.methods))517+518+ rule_methods = [519+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520+ ]521+522+ headers = ('Endpoint', 'Methods', 'Rule')523+ widths = (524+ max(len(rule.endpoint) for rule in rules),525+ max(len(methods) for methods in rule_methods),526+ max(len(rule.rule) for rule in rules),527+ )528+ widths = [max(len(h), w) for h, w in zip(headers, widths)]529+ row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)530+531+ click.echo(row.format(*headers).strip())532+ click.echo(row.format(*('-' * width for width in widths)))533+534+ for rule, methods in zip(rules, rule_methods):535+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536+537+538 cli = FlaskGroup(help="""\539 This shell command acts as general utility script for Flask applications.540 541 It loads the application configured (through the FLASK_APP environment39 unmodified linesmodified:tests/test_cli.py+69 added-9 removed
12 unmodified lines13 #14 from __future__ import absolute_import, print_function15 import os16 import sys17+from functools import partial18 19 import click20 import pytest21 from click.testing import CliRunner22 from flask import Flask, current_app23 23-from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24+from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version27 28 29+@pytest.fixture30+def runner():31+ return CliRunner()32+33+34 def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name96 unmodified lines134 assert app.name == "createapp"135 assert obj.load_app() == app136 137 132-def test_with_appcontext():138+def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144 145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146 141- runner = CliRunner()147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150 151 147-def test_appgroup():152+def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass11 unmodified lines168 click.echo(current_app.name)169 170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171 167- runner = CliRunner()172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175 1 unmodified line177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179 180 177-def test_flaskgroup():181+def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185 4 unmodified lines190 @cli.command()191 def test():192 click.echo(current_app.name)193 190- runner = CliRunner()194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197 198 196-def test_print_exceptions():199+def test_print_exceptions(runner):200 """Print the stacktrace if the CLI."""201 def create_app(info):202 raise Exception("oh no")203 return Flask("flaskgroup")1 unmodified line205 @click.group(cls=FlaskGroup, create_app=create_app)206 def cli(**params):207 pass208 206- runner = CliRunner()209 result = runner.invoke(cli, ['--help'])210 assert result.exit_code == 0211 assert 'Exception: oh no' in result.output212 assert 'Traceback' in result.output213+214+215+class TestRoutes:216+ @pytest.fixture217+ def invoke(self, runner):218+ def create_app(info):219+ app = Flask(__name__)220+ app.testing = True221+222+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223+ def yyy_get_post(x, y):224+ pass225+226+ @app.route('/zzz_post', methods=['POST'])227+ def aaa_post():228+ pass229+230+ return app231+232+ cli = FlaskGroup(create_app=create_app)233+ return partial(runner.invoke, cli)234+235+ def expect_order(self, order, output):236+ # skip the header and match the start of each row237+ for expect, line in zip(order, output.splitlines()[2:]):238+ # do this instead of startswith for nicer pytest output239+ assert line[:len(expect)] == expect240+241+ def test_simple(self, invoke):242+ result = invoke(['routes'])243+ assert result.exit_code == 0244+ self.expect_order(245+ ['aaa_post', 'static', 'yyy_get_post'],246+ result.output247+ )248+249+ def test_sort(self, invoke):250+ default_output = invoke(['routes']).output251+ endpoint_output = invoke(['routes', '-s', 'endpoint']).output252+ assert default_output == endpoint_output253+ self.expect_order(254+ ['static', 'yyy_get_post', 'aaa_post'],255+ invoke(['routes', '-s', 'methods']).output256+ )257+ self.expect_order(258+ ['yyy_get_post', 'static', 'aaa_post'],259+ invoke(['routes', '-s', 'rule']).output260+ )261+ self.expect_order(262+ ['aaa_post', 'yyy_get_post', 'static'],263+ invoke(['routes', '-s', 'match']).output264+ )265+266+ def test_all_methods(self, invoke):267+ output = invoke(['routes']).output268+ assert 'GET, HEAD, OPTIONS, POST' not in output269+ output = invoke(['routes', '--all-methods']).output270+ assert 'GET, HEAD, OPTIONS, POST' in outputmodified:CHANGES+3 added
30 unmodified lines31 override the app's encoder and decoder. (`#1898`_)32 - ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33 bad response types. The error messages have been improved to describe why the34 type is invalid. (`#2256`_)35+- Add ``routes`` CLI command to output routes registered on the application.36+ (`#2259`_)37 38 .. _#1489: https://github.com/pallets/flask/pull/148939 .. _#1898: https://github.com/pallets/flask/pull/189840 .. _#1936: https://github.com/pallets/flask/pull/193641 .. _#2017: https://github.com/pallets/flask/pull/201742 .. _#2223: https://github.com/pallets/flask/pull/222343 .. _#2254: https://github.com/pallets/flask/pull/225444 .. _#2256: https://github.com/pallets/flask/pull/225645+.. _#2259: https://github.com/pallets/flask/pull/225946 47 Version 0.12.148 --------------49 608 unmodified lines