cli.py
This file
Path
src/flask/cli.py
994 lines · 31.3 KiB · Python
Last changed by
Merge pull request #3972 from ThiefMaster/click-7David Lordbefore adoption77db3d5
History of this fileTake it
1import ast2import inspect3import os4import platform5import re6import sys7import traceback8import warnings9from functools import update_wrapper10from operator import attrgetter11from threading import Lock12from threading import Thread1314import click15from werkzeug.utils import import_string1617from .globals import current_app18from .helpers import get_debug_flag19from .helpers import get_env20from .helpers import get_load_dotenv2122try:23 import dotenv24except ImportError:25 dotenv = None2627try:28 import ssl29except ImportError:30 ssl = None # type: ignore313233class NoAppException(click.UsageError):34 """Raised if an application cannot be found or loaded."""353637def find_best_app(script_info, module):38 """Given a module instance this tries to find the best possible39 application in the module or raises an exception.40 """41 from . import Flask4243 # Search for the most common names first.44 for attr_name in ("app", "application"):45 app = getattr(module, attr_name, None)4647 if isinstance(app, Flask):48 return app4950 # Otherwise find the only object that is a Flask instance.51 matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]5253 if len(matches) == 1:54 return matches[0]55 elif len(matches) > 1:56 raise NoAppException(57 "Detected multiple Flask applications in module"58 f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"59 f" to specify the correct one."60 )6162 # Search for app factory functions.63 for attr_name in ("create_app", "make_app"):64 app_factory = getattr(module, attr_name, None)6566 if inspect.isfunction(app_factory):67 try:68 app = call_factory(script_info, app_factory)6970 if isinstance(app, Flask):71 return app72 except TypeError:73 if not _called_with_wrong_args(app_factory):74 raise75 raise NoAppException(76 f"Detected factory {attr_name!r} in module {module.__name__!r},"77 " but could not call it without arguments. Use"78 f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""79 " to specify arguments."80 )8182 raise NoAppException(83 "Failed to find Flask application or factory in module"84 f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"85 " to specify one."86 )878889def call_factory(script_info, app_factory, args=None, kwargs=None):90 """Takes an app factory, a ``script_info` object and optionally a tuple91 of arguments. Checks for the existence of a script_info argument and calls92 the app_factory depending on that and the arguments provided.93 """94 sig = inspect.signature(app_factory)95 args = [] if args is None else args96 kwargs = {} if kwargs is None else kwargs9798 if "script_info" in sig.parameters:99 warnings.warn(100 "The 'script_info' argument is deprecated and will not be"101 " passed to the app factory function in Flask 2.1.",102 DeprecationWarning,103 )104 kwargs["script_info"] = script_info105106 if (107 not args108 and len(sig.parameters) == 1109 and next(iter(sig.parameters.values())).default is inspect.Parameter.empty110 ):111 warnings.warn(112 "Script info is deprecated and will not be passed as the"113 " single argument to the app factory function in Flask"114 " 2.1.",115 DeprecationWarning,116 )117 args.append(script_info)118119 return app_factory(*args, **kwargs)120121122def _called_with_wrong_args(f):123 """Check whether calling a function raised a ``TypeError`` because124 the call failed or because something in the factory raised the125 error.126127 :param f: The function that was called.128 :return: ``True`` if the call failed.129 """130 tb = sys.exc_info()[2]131132 try:133 while tb is not None:134 if tb.tb_frame.f_code is f.__code__:135 # In the function, it was called successfully.136 return False137138 tb = tb.tb_next139140 # Didn't reach the function.141 return True142 finally:143 # Delete tb to break a circular reference.144 # https://docs.python.org/2/library/sys.html#sys.exc_info145 del tb146147148def find_app_by_string(script_info, module, app_name):149 """Check if the given string is a variable name or a function. Call150 a function to get the app instance, or return the variable directly.151 """152 from . import Flask153154 # Parse app_name as a single expression to determine if it's a valid155 # attribute name or function call.156 try:157 expr = ast.parse(app_name.strip(), mode="eval").body158 except SyntaxError:159 raise NoAppException(160 f"Failed to parse {app_name!r} as an attribute name or function call."161 )162163 if isinstance(expr, ast.Name):164 name = expr.id165 args = kwargs = None166 elif isinstance(expr, ast.Call):167 # Ensure the function name is an attribute name only.168 if not isinstance(expr.func, ast.Name):169 raise NoAppException(170 f"Function reference must be a simple name: {app_name!r}."171 )172173 name = expr.func.id174175 # Parse the positional and keyword arguments as literals.176 try:177 args = [ast.literal_eval(arg) for arg in expr.args]178 kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}179 except ValueError:180 # literal_eval gives cryptic error messages, show a generic181 # message with the full expression instead.182 raise NoAppException(183 f"Failed to parse arguments as literal values: {app_name!r}."184 )185 else:186 raise NoAppException(187 f"Failed to parse {app_name!r} as an attribute name or function call."188 )189190 try:191 attr = getattr(module, name)192 except AttributeError:193 raise NoAppException(194 f"Failed to find attribute {name!r} in {module.__name__!r}."195 )196197 # If the attribute is a function, call it with any args and kwargs198 # to get the real application.199 if inspect.isfunction(attr):200 try:201 app = call_factory(script_info, attr, args, kwargs)202 except TypeError:203 if not _called_with_wrong_args(attr):204 raise205206 raise NoAppException(207 f"The factory {app_name!r} in module"208 f" {module.__name__!r} could not be called with the"209 " specified arguments."210 )211 else:212 app = attr213214 if isinstance(app, Flask):215 return app216217 raise NoAppException(218 "A valid Flask application was not obtained from"219 f" '{module.__name__}:{app_name}'."220 )221222223def prepare_import(path):224 """Given a filename this will try to calculate the python path, add it225 to the search path and return the actual module name that is expected.226 """227 path = os.path.realpath(path)228229 fname, ext = os.path.splitext(path)230 if ext == ".py":231 path = fname232233 if os.path.basename(path) == "__init__":234 path = os.path.dirname(path)235236 module_name = []237238 # move up until outside package structure (no __init__.py)239 while True:240 path, name = os.path.split(path)241 module_name.append(name)242243 if not os.path.exists(os.path.join(path, "__init__.py")):244 break245246 if sys.path[0] != path:247 sys.path.insert(0, path)248249 return ".".join(module_name[::-1])250251252def locate_app(script_info, module_name, app_name, raise_if_not_found=True):253 __traceback_hide__ = True # noqa: F841254255 try:256 __import__(module_name)257 except ImportError:258 # Reraise the ImportError if it occurred within the imported module.259 # Determine this by checking whether the trace has a depth > 1.260 if sys.exc_info()[2].tb_next:261 raise NoAppException(262 f"While importing {module_name!r}, an ImportError was"263 f" raised:\n\n{traceback.format_exc()}"264 )265 elif raise_if_not_found:266 raise NoAppException(f"Could not import {module_name!r}.")267 else:268 return269270 module = sys.modules[module_name]271272 if app_name is None:273 return find_best_app(script_info, module)274 else:275 return find_app_by_string(script_info, module, app_name)276277278def get_version(ctx, param, value):279 if not value or ctx.resilient_parsing:280 return281282 import werkzeug283 from . import __version__284285 click.echo(286 f"Python {platform.python_version()}\n"287 f"Flask {__version__}\n"288 f"Werkzeug {werkzeug.__version__}",289 color=ctx.color,290 )291 ctx.exit()292293294version_option = click.Option(295 ["--version"],296 help="Show the flask version",297 expose_value=False,298 callback=get_version,299 is_flag=True,300 is_eager=True,301)302303304class DispatchingApp:305 """Special application that dispatches to a Flask application which306 is imported by name in a background thread. If an error happens307 it is recorded and shown as part of the WSGI handling which in case308 of the Werkzeug debugger means that it shows up in the browser.309 """310311 def __init__(self, loader, use_eager_loading=None):312 self.loader = loader313 self._app = None314 self._lock = Lock()315 self._bg_loading_exc_info = None316317 if use_eager_loading is None:318 use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"319320 if use_eager_loading:321 self._load_unlocked()322 else:323 self._load_in_background()324325 def _load_in_background(self):326 def _load_app():327 __traceback_hide__ = True # noqa: F841328 with self._lock:329 try:330 self._load_unlocked()331 except Exception:332 self._bg_loading_exc_info = sys.exc_info()333334 t = Thread(target=_load_app, args=())335 t.start()336337 def _flush_bg_loading_exception(self):338 __traceback_hide__ = True # noqa: F841339 exc_info = self._bg_loading_exc_info340 if exc_info is not None:341 self._bg_loading_exc_info = None342 raise exc_info343344 def _load_unlocked(self):345 __traceback_hide__ = True # noqa: F841346 self._app = rv = self.loader()347 self._bg_loading_exc_info = None348 return rv349350 def __call__(self, environ, start_response):351 __traceback_hide__ = True # noqa: F841352 if self._app is not None:353 return self._app(environ, start_response)354 self._flush_bg_loading_exception()355 with self._lock:356 if self._app is not None:357 rv = self._app358 else:359 rv = self._load_unlocked()360 return rv(environ, start_response)361362363class ScriptInfo:364 """Helper object to deal with Flask applications. This is usually not365 necessary to interface with as it's used internally in the dispatching366 to click. In future versions of Flask this object will most likely play367 a bigger role. Typically it's created automatically by the368 :class:`FlaskGroup` but you can also manually create it and pass it369 onwards as click object.370 """371372 def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):373 #: Optionally the import path for the Flask application.374 self.app_import_path = app_import_path or os.environ.get("FLASK_APP")375 #: Optionally a function that is passed the script info to create376 #: the instance of the application.377 self.create_app = create_app378 #: A dictionary with arbitrary data that can be associated with379 #: this script info.380 self.data = {}381 self.set_debug_flag = set_debug_flag382 self._loaded_app = None383384 def load_app(self):385 """Loads the Flask app (if not yet loaded) and returns it. Calling386 this multiple times will just result in the already loaded app to387 be returned.388 """389 __traceback_hide__ = True # noqa: F841390391 if self._loaded_app is not None:392 return self._loaded_app393394 if self.create_app is not None:395 app = call_factory(self, self.create_app)396 else:397 if self.app_import_path:398 path, name = (399 re.split(r":(?![\\/])", self.app_import_path, 1) + [None]400 )[:2]401 import_name = prepare_import(path)402 app = locate_app(self, import_name, name)403 else:404 for path in ("wsgi.py", "app.py"):405 import_name = prepare_import(path)406 app = locate_app(self, import_name, None, raise_if_not_found=False)407408 if app:409 break410411 if not app:412 raise NoAppException(413 "Could not locate a Flask application. You did not provide "414 'the "FLASK_APP" environment variable, and a "wsgi.py" or '415 '"app.py" module was not found in the current directory.'416 )417418 if self.set_debug_flag:419 # Update the app's debug flag through the descriptor so that420 # other values repopulate as well.421 app.debug = get_debug_flag()422423 self._loaded_app = app424 return app425426427pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)428429430def with_appcontext(f):431 """Wraps a callback so that it's guaranteed to be executed with the432 script's application context. If callbacks are registered directly433 to the ``app.cli`` object then they are wrapped with this function434 by default unless it's disabled.435 """436437 @click.pass_context438 def decorator(__ctx, *args, **kwargs):439 with __ctx.ensure_object(ScriptInfo).load_app().app_context():440 return __ctx.invoke(f, *args, **kwargs)441442 return update_wrapper(decorator, f)443444445class AppGroup(click.Group):446 """This works similar to a regular click :class:`~click.Group` but it447 changes the behavior of the :meth:`command` decorator so that it448 automatically wraps the functions in :func:`with_appcontext`.449450 Not to be confused with :class:`FlaskGroup`.451 """452453 def command(self, *args, **kwargs):454 """This works exactly like the method of the same name on a regular455 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`456 unless it's disabled by passing ``with_appcontext=False``.457 """458 wrap_for_ctx = kwargs.pop("with_appcontext", True)459460 def decorator(f):461 if wrap_for_ctx:462 f = with_appcontext(f)463 return click.Group.command(self, *args, **kwargs)(f)464465 return decorator466467 def group(self, *args, **kwargs):468 """This works exactly like the method of the same name on a regular469 :class:`click.Group` but it defaults the group class to470 :class:`AppGroup`.471 """472 kwargs.setdefault("cls", AppGroup)473 return click.Group.group(self, *args, **kwargs)474475476class FlaskGroup(AppGroup):477 """Special subclass of the :class:`AppGroup` group that supports478 loading more commands from the configured Flask app. Normally a479 developer does not have to interface with this class but there are480 some very advanced use cases for which it makes sense to create an481 instance of this. see :ref:`custom-scripts`.482483 :param add_default_commands: if this is True then the default run and484 shell commands will be added.485 :param add_version_option: adds the ``--version`` option.486 :param create_app: an optional callback that is passed the script info and487 returns the loaded app.488 :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`489 files to set environment variables. Will also change the working490 directory to the directory containing the first file found.491 :param set_debug_flag: Set the app's debug flag based on the active492 environment493494 .. versionchanged:: 1.0495 If installed, python-dotenv will be used to load environment variables496 from :file:`.env` and :file:`.flaskenv` files.497 """498499 def __init__(500 self,501 add_default_commands=True,502 create_app=None,503 add_version_option=True,504 load_dotenv=True,505 set_debug_flag=True,506 **extra,507 ):508 params = list(extra.pop("params", None) or ())509510 if add_version_option:511 params.append(version_option)512513 AppGroup.__init__(self, params=params, **extra)514 self.create_app = create_app515 self.load_dotenv = load_dotenv516 self.set_debug_flag = set_debug_flag517518 if add_default_commands:519 self.add_command(run_command)520 self.add_command(shell_command)521 self.add_command(routes_command)522523 self._loaded_plugin_commands = False524525 def _load_plugin_commands(self):526 if self._loaded_plugin_commands:527 return528 try:529 import pkg_resources530 except ImportError:531 self._loaded_plugin_commands = True532 return533534 for ep in pkg_resources.iter_entry_points("flask.commands"):535 self.add_command(ep.load(), ep.name)536 self._loaded_plugin_commands = True537538 def get_command(self, ctx, name):539 self._load_plugin_commands()540 # Look up built-in and plugin commands, which should be541 # available even if the app fails to load.542 rv = super().get_command(ctx, name)543544 if rv is not None:545 return rv546547 info = ctx.ensure_object(ScriptInfo)548549 # Look up commands provided by the app, showing an error and550 # continuing if the app couldn't be loaded.551 try:552 return info.load_app().cli.get_command(ctx, name)553 except NoAppException as e:554 click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")555556 def list_commands(self, ctx):557 self._load_plugin_commands()558 # Start with the built-in and plugin commands.559 rv = set(super().list_commands(ctx))560 info = ctx.ensure_object(ScriptInfo)561562 # Add commands provided by the app, showing an error and563 # continuing if the app couldn't be loaded.564 try:565 rv.update(info.load_app().cli.list_commands(ctx))566 except NoAppException as e:567 # When an app couldn't be loaded, show the error message568 # without the traceback.569 click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")570 except Exception:571 # When any other errors occurred during loading, show the572 # full traceback.573 click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")574575 return sorted(rv)576577 def main(self, *args, **kwargs):578 # Set a global flag that indicates that we were invoked from the579 # command line interface. This is detected by Flask.run to make the580 # call into a no-op. This is necessary to avoid ugly errors when the581 # script that is loaded here also attempts to start a server.582 os.environ["FLASK_RUN_FROM_CLI"] = "true"583584 if get_load_dotenv(self.load_dotenv):585 load_dotenv()586587 obj = kwargs.get("obj")588589 if obj is None:590 obj = ScriptInfo(591 create_app=self.create_app, set_debug_flag=self.set_debug_flag592 )593594 kwargs["obj"] = obj595 kwargs.setdefault("auto_envvar_prefix", "FLASK")596 return super().main(*args, **kwargs)597598599def _path_is_ancestor(path, other):600 """Take ``other`` and remove the length of ``path`` from it. Then join it601 to ``path``. If it is the original value, ``path`` is an ancestor of602 ``other``."""603 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other604605606def load_dotenv(path=None):607 """Load "dotenv" files in order of precedence to set environment variables.608609 If an env var is already set it is not overwritten, so earlier files in the610 list are preferred over later files.611612 This is a no-op if `python-dotenv`_ is not installed.613614 .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme615616 :param path: Load the file at this location instead of searching.617 :return: ``True`` if a file was loaded.618619 .. versionchanged:: 1.1.0620 Returns ``False`` when python-dotenv is not installed, or when621 the given path isn't a file.622623 .. versionchanged:: 2.0624 When loading the env files, set the default encoding to UTF-8.625626 .. versionadded:: 1.0627 """628 if dotenv is None:629 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):630 click.secho(631 " * Tip: There are .env or .flaskenv files present."632 ' Do "pip install python-dotenv" to use them.',633 fg="yellow",634 err=True,635 )636637 return False638639 # if the given path specifies the actual file then return True,640 # else False641 if path is not None:642 if os.path.isfile(path):643 return dotenv.load_dotenv(path, encoding="utf-8")644645 return False646647 new_dir = None648649 for name in (".env", ".flaskenv"):650 path = dotenv.find_dotenv(name, usecwd=True)651652 if not path:653 continue654655 if new_dir is None:656 new_dir = os.path.dirname(path)657658 dotenv.load_dotenv(path, encoding="utf-8")659660 return new_dir is not None # at least one file was located and loaded661662663def show_server_banner(env, debug, app_import_path, eager_loading):664 """Show extra startup messages the first time the server is run,665 ignoring the reloader.666 """667 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":668 return669670 if app_import_path is not None:671 message = f" * Serving Flask app {app_import_path!r}"672673 if not eager_loading:674 message += " (lazy loading)"675676 click.echo(message)677678 click.echo(f" * Environment: {env}")679680 if env == "production":681 click.secho(682 " WARNING: This is a development server. Do not use it in"683 " a production deployment.",684 fg="red",685 )686 click.secho(" Use a production WSGI server instead.", dim=True)687688 if debug is not None:689 click.echo(f" * Debug mode: {'on' if debug else 'off'}")690691692class CertParamType(click.ParamType):693 """Click option type for the ``--cert`` option. Allows either an694 existing file, the string ``'adhoc'``, or an import for a695 :class:`~ssl.SSLContext` object.696 """697698 name = "path"699700 def __init__(self):701 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)702703 def convert(self, value, param, ctx):704 if ssl is None:705 raise click.BadParameter(706 'Using "--cert" requires Python to be compiled with SSL support.',707 ctx,708 param,709 )710711 try:712 return self.path_type(value, param, ctx)713 except click.BadParameter:714 value = click.STRING(value, param, ctx).lower()715716 if value == "adhoc":717 try:718 import cryptography # noqa: F401719 except ImportError:720 raise click.BadParameter(721 "Using ad-hoc certificates requires the cryptography library.",722 ctx,723 param,724 )725726 return value727728 obj = import_string(value, silent=True)729730 if isinstance(obj, ssl.SSLContext):731 return obj732733 raise734735736def _validate_key(ctx, param, value):737 """The ``--key`` option must be specified when ``--cert`` is a file.738 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.739 """740 cert = ctx.params.get("cert")741 is_adhoc = cert == "adhoc"742 is_context = ssl and isinstance(cert, ssl.SSLContext)743744 if value is not None:745 if is_adhoc:746 raise click.BadParameter(747 'When "--cert" is "adhoc", "--key" is not used.', ctx, param748 )749750 if is_context:751 raise click.BadParameter(752 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param753 )754755 if not cert:756 raise click.BadParameter('"--cert" must also be specified.', ctx, param)757758 ctx.params["cert"] = cert, value759760 else:761 if cert and not (is_adhoc or is_context):762 raise click.BadParameter('Required when using "--cert".', ctx, param)763764 return value765766767class SeparatedPathType(click.Path):768 """Click option type that accepts a list of values separated by the769 OS's path separator (``:``, ``;`` on Windows). Each value is770 validated as a :class:`click.Path` type.771 """772773 def convert(self, value, param, ctx):774 items = self.split_envvar_value(value)775 super_convert = super().convert776 return [super_convert(item, param, ctx) for item in items]777778779@click.command("run", short_help="Run a development server.")780@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")781@click.option("--port", "-p", default=5000, help="The port to bind to.")782@click.option(783 "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."784)785@click.option(786 "--key",787 type=click.Path(exists=True, dir_okay=False, resolve_path=True),788 callback=_validate_key,789 expose_value=False,790 help="The key file to use when specifying a certificate.",791)792@click.option(793 "--reload/--no-reload",794 default=None,795 help="Enable or disable the reloader. By default the reloader "796 "is active if debug is enabled.",797)798@click.option(799 "--debugger/--no-debugger",800 default=None,801 help="Enable or disable the debugger. By default the debugger "802 "is active if debug is enabled.",803)804@click.option(805 "--eager-loading/--lazy-loading",806 default=None,807 help="Enable or disable eager loading. By default eager "808 "loading is enabled if the reloader is disabled.",809)810@click.option(811 "--with-threads/--without-threads",812 default=True,813 help="Enable or disable multithreading.",814)815@click.option(816 "--extra-files",817 default=None,818 type=SeparatedPathType(),819 help=(820 "Extra files that trigger a reload on change. Multiple paths"821 f" are separated by {os.path.pathsep!r}."822 ),823)824@pass_script_info825def run_command(826 info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files827):828 """Run a local development server.829830 This server is for development purposes only. It does not provide831 the stability, security, or performance of production WSGI servers.832833 The reloader and debugger are enabled by default if834 FLASK_ENV=development or FLASK_DEBUG=1.835 """836 debug = get_debug_flag()837838 if reload is None:839 reload = debug840841 if debugger is None:842 debugger = debug843844 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)845 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)846847 from werkzeug.serving import run_simple848849 run_simple(850 host,851 port,852 app,853 use_reloader=reload,854 use_debugger=debugger,855 threaded=with_threads,856 ssl_context=cert,857 extra_files=extra_files,858 )859860861@click.command("shell", short_help="Run a shell in the app context.")862@with_appcontext863def shell_command() -> None:864 """Run an interactive Python shell in the context of a given865 Flask application. The application will populate the default866 namespace of this shell according to its configuration.867868 This is useful for executing small snippets of management code869 without having to manually configure the application.870 """871 import code872 from .globals import _app_ctx_stack873874 app = _app_ctx_stack.top.app875 banner = (876 f"Python {sys.version} on {sys.platform}\n"877 f"App: {app.import_name} [{app.env}]\n"878 f"Instance: {app.instance_path}"879 )880 ctx: dict = {}881882 # Support the regular Python interpreter startup script if someone883 # is using it.884 startup = os.environ.get("PYTHONSTARTUP")885 if startup and os.path.isfile(startup):886 with open(startup) as f:887 eval(compile(f.read(), startup, "exec"), ctx)888889 ctx.update(app.make_shell_context())890891 # Site, customize, or startup script can set a hook to call when892 # entering interactive mode. The default one sets up readline with893 # tab and history completion.894 interactive_hook = getattr(sys, "__interactivehook__", None)895896 if interactive_hook is not None:897 try:898 import readline899 from rlcompleter import Completer900 except ImportError:901 pass902 else:903 # rlcompleter uses __main__.__dict__ by default, which is904 # flask.__main__. Use the shell context instead.905 readline.set_completer(Completer(ctx).complete)906907 interactive_hook()908909 code.interact(banner=banner, local=ctx)910911912@click.command("routes", short_help="Show the routes for the app.")913@click.option(914 "--sort",915 "-s",916 type=click.Choice(("endpoint", "methods", "rule", "match")),917 default="endpoint",918 help=(919 'Method to sort routes by. "match" is the order that Flask will match '920 "routes when dispatching a request."921 ),922)923@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")924@with_appcontext925def routes_command(sort: str, all_methods: bool) -> None:926 """Show all registered routes with endpoints and methods."""927928 rules = list(current_app.url_map.iter_rules())929 if not rules:930 click.echo("No routes were registered.")931 return932933 ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))934935 if sort in ("endpoint", "rule"):936 rules = sorted(rules, key=attrgetter(sort))937 elif sort == "methods":938 rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore939940 rule_methods = [941 ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore942 for rule in rules943 ]944945 headers = ("Endpoint", "Methods", "Rule")946 widths = (947 max(len(rule.endpoint) for rule in rules),948 max(len(methods) for methods in rule_methods),949 max(len(rule.rule) for rule in rules),950 )951 widths = [max(len(h), w) for h, w in zip(headers, widths)]952 row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)953954 click.echo(row.format(*headers).strip())955 click.echo(row.format(*("-" * width for width in widths)))956957 for rule, methods in zip(rules, rule_methods):958 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())959960961cli = FlaskGroup(962 help="""\963A general utility script for Flask applications.964965Provides commands from Flask, extensions, and the application. Loads the966application defined in the FLASK_APP environment variable, or from a wsgi.py967file. Setting the FLASK_ENV environment variable to 'development' will enable968debug mode.969970\b971 {prefix}{cmd} FLASK_APP=hello.py972 {prefix}{cmd} FLASK_ENV=development973 {prefix}flask run974""".format(975 cmd="export" if os.name == "posix" else "set",976 prefix="$ " if os.name == "posix" else "> ",977 )978)979980981def main() -> None:982 if int(click.__version__[0]) < 8:983 warnings.warn(984 "Using the `flask` cli with Click 7 is deprecated and"985 " will not be supported starting with Flask 2.1."986 " Please upgrade to Click 8 as soon as possible.",987 DeprecationWarning,988 )989 # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed990 cli.main(args=sys.argv[1:])991992993if __name__ == "__main__":994 main()