Skip to content
Myr

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

4 files+102 added−73 removed

modified:flask/cli.py+45 added-25 removed
10 unmodified lines
1112import os13import sys14import traceback15from threading import Lock, Thread15from functools import update_wrapper16from operator import attrgetter17from threading import Lock, Thread1819import click2021from . import __version__22from ._compat import iteritems, reraise23from .globals import current_app24from .helpers import get_debug_flag22from . import __version__252627class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""2930
456 unmodified lines
487488 code.interact(banner=banner, local=ctx)489490488@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_appcontext493def 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.app507def routes_command(sort, all_methods):508 """Show all registered routes with endpoints and methods."""509498 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'))512501 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))517508 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 ]521513 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)530531 click.echo(row.format(*headers).strip())532 click.echo(row.format(*('-' * width for width in widths)))533534 for rule, methods in zip(rules, rule_methods):535 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536537538cli = FlaskGroup(help="""\539This shell command acts as general utility script for Flask applications.540541It loads the application configured (through the FLASK_APP environment
39 unmodified lines
deleted:tests/test_apps/cliapp/routesapp.py-18 removed
1from __future__ import absolute_import, print_function23from flask import Flask456noroute_app = Flask('noroute app')7simpleroute_app = Flask('simpleroute app')8only_POST_route_app = Flask('GET route app')91011@simpleroute_app.route('/simpleroute')12def simple():13 pass141516@only_POST_route_app.route('/only-post', methods=['POST'])17def only_post():18 pass
modified:tests/test_cli.py+54 added-30 removed
12 unmodified lines
13#14from __future__ import absolute_import, print_function15import os16import sys17from functools import partial1819import click20import pytest21from click.testing import CliRunner
173 unmodified lines
195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197198198def test_print_exceptions():199def 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 line
205 @click.group(cls=FlaskGroup, create_app=create_app)206 def cli(**params):207 pass208208 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.output213214215class 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 == """\221Route 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 = True221226 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 == """\231Route 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 pass225237 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 pass229230 return app231232 cli = FlaskGroup(create_app=create_app)233 return partial(runner.invoke, cli)234235 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)] == expect240241 def test_simple(self, invoke):242 result = invoke(['routes'])243 assert result.exit_code == 0241 assert result.output == """\242Route 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 )248249 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 )265266 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 output
modified:CHANGES+3 added
30 unmodified lines
31 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`_)3738.. _#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/22594647Version 0.12.148--------------49
608 unmodified lines