add sort by match order
Before adoption: this commit came in with the history the project adopted, so no landing records it.
sort by endpoint by default combine sort flags sort methods ignore HEAD and OPTIONS methods by default rearrange columns use format to build row format string rework tests add changelog
authored by David Lord · committed by David Lord · parent 717e45a · Browse files · 4 files·+102 added−73 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+102 added−73 removed
- tests:+54 added−48 removed
- other:+48 added−25 removed
Provenance
- Commit
7ad7958- Tree
e32bca1- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
717e45a
4 files changed+102 added−73 removed
modified:flask/cli.py+45 added-25 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 456 unmodified lines487 488 code.interact(banner=banner, local=ctx)489 490 488-@click.command('routes', short_help='Show routes for the app.')489-@click.option('-r', 'order_by', flag_value='rule', default=True, help='Order by route')490-@click.option('-e', 'order_by', flag_value='endpoint', help='Order by endpoint')491-@click.option('-m', 'order_by', flag_value='methods', help='Order by methods')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_appcontext493-def routes_command(order_by):494- """Show all routes with endpoints and methods."""495- from flask.globals import _app_ctx_stack496- app = _app_ctx_stack.top.app507+def routes_command(sort, all_methods):508+ """Show all registered routes with endpoints and methods."""509 498- order_key = lambda rule: getattr(rule, order_by)499- sorted_rules = sorted(app.url_map.iter_rules(), key=order_key)510+ rules = list(current_app.url_map.iter_rules())511+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512 501- max_rule = max(len(rule.rule) for rule in sorted_rules)502- max_rule = max(max_rule, len('Route'))503- max_ep = max(len(rule.endpoint) for rule in sorted_rules)504- max_ep = max(max_ep, len('Endpoint'))505- max_meth = max(len(', '.join(rule.methods)) for rule in sorted_rules)506- max_meth = max(max_meth, len('Methods'))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 508- columnformat = '{:<%s} {:<%s} {:<%s}' % (max_rule, max_ep, max_meth)509- click.echo(columnformat.format('Route', 'Endpoint', 'Methods'))510- under_count = max_rule + max_ep + max_meth + 4511- click.echo('-' * under_count)518+ rule_methods = [519+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520+ ]521 513- for rule in sorted_rules:514- methods = ', '.join(rule.methods)515- click.echo(columnformat.format(rule.rule, rule.endpoint, methods))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 linesdeleted:tests/test_apps/cliapp/routesapp.py-18 removed
1-from __future__ import absolute_import, print_function2-3-from flask import Flask4-5-6-noroute_app = Flask('noroute app')7-simpleroute_app = Flask('simpleroute app')8-only_POST_route_app = Flask('GET route app')9-10-11-@simpleroute_app.route('/simpleroute')12-def simple():13- pass14-15-16-@only_POST_route_app.route('/only-post', methods=['POST'])17-def only_post():18- passmodified:tests/test_cli.py+54 added-30 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 CliRunner173 unmodified lines195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197 198 198-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 208- 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- def test_no_route(self, runner, monkeypatch):217- monkeypatch.setitem(os.environ, 'FLASK_APP', 'cliapp.routesapp:noroute_app')218- result = runner.invoke(cli, ['routes'], catch_exceptions=False)219- assert result.exit_code == 0220- assert result.output == """\221-Route Endpoint Methods 222------------------------------------------------------223-/static/<path:filename> static HEAD, OPTIONS, GET224-"""216+ @pytest.fixture217+ def invoke(self, runner):218+ def create_app(info):219+ app = Flask(__name__)220+ app.testing = True221 226- def test_simple_route(self, runner, monkeypatch):227- monkeypatch.setitem(os.environ, 'FLASK_APP', 'cliapp.routesapp:simpleroute_app')228- result = runner.invoke(cli, ['routes'], catch_exceptions=False)229- assert result.exit_code == 0230- assert result.output == """\231-Route Endpoint Methods 232------------------------------------------------------233-/simpleroute simple HEAD, OPTIONS, GET234-/static/<path:filename> static HEAD, OPTIONS, GET235-"""222+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223+ def yyy_get_post(x, y):224+ pass225 237- def test_only_POST_route(self, runner, monkeypatch):238- monkeypatch.setitem(os.environ, 'FLASK_APP', 'cliapp.routesapp:only_POST_route_app')239- result = runner.invoke(cli, ['routes'], catch_exceptions=False)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 == 0241- assert result.output == """\242-Route Endpoint Methods 243-------------------------------------------------------244-/only-post only_post POST, OPTIONS 245-/static/<path:filename> static HEAD, OPTIONS, GET246-"""244+ 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