Skip to content
Myr

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

3 files+125 added−11 removed

modified:flask/cli.py+53 added-2 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
290 unmodified lines
321322 if add_default_commands:323 self.add_command(run_command)324 self.add_command(shell_command)325 self.add_command(routes_command)326327 self._loaded_plugin_commands = False328329 def _load_plugin_commands(self):
157 unmodified lines
487488 code.interact(banner=banner, local=ctx)489490491@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_appcontext507def routes_command(sort, all_methods):508 """Show all registered routes with endpoints and methods."""509510 rules = list(current_app.url_map.iter_rules())511 ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512513 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))517518 rule_methods = [519 ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520 ]521522 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
modified:tests/test_cli.py+69 added-9 removed
12 unmodified lines
13#14from __future__ import absolute_import, print_function15import os16import sys17from functools import partial1819import click20import pytest21from click.testing import CliRunner22from flask import Flask, current_app2323from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24from 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_version272829@pytest.fixture30def runner():31 return CliRunner()323334def 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.name
96 unmodified lines
134 assert app.name == "createapp"135 assert obj.load_app() == app136137132def test_with_appcontext():138def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146141 runner = CliRunner()147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150151147def test_appgroup():152def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass
11 unmodified lines
168 click.echo(current_app.name)169170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171167 runner = CliRunner()172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175
1 unmodified line
177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179180177def test_flaskgroup():181def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185
4 unmodified lines
190 @cli.command()191 def test():192 click.echo(current_app.name)193190 runner = CliRunner()194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197198196def 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 pass208206 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 @pytest.fixture217 def invoke(self, runner):218 def create_app(info):219 app = Flask(__name__)220 app.testing = True221222 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223 def yyy_get_post(x, y):224 pass225226 @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 == 0244 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