Skip to content
Myr

cli.py

This file

Path

src/flask/cli.py

1,158 lines · 35.9 KiB · Python

Last changed by

Merge pull request #4682 from pallets/refactor-context-stackDavid Lordbefore adoptioncbebdae

History of this file

Take it

1from __future__ import annotations23import ast4import inspect5import os6import platform7import re8import sys9import traceback10import typing as t11from functools import update_wrapper12from operator import attrgetter13from threading import Lock14from threading import Thread1516import click17from click.core import ParameterSource18from werkzeug.serving import is_running_from_reloader19from werkzeug.utils import import_string2021from .globals import current_app22from .helpers import get_debug_flag23from .helpers import get_env24from .helpers import get_load_dotenv2526if t.TYPE_CHECKING:27    from .app import Flask282930class NoAppException(click.UsageError):31    """Raised if an application cannot be found or loaded."""323334def find_best_app(module):35    """Given a module instance this tries to find the best possible36    application in the module or raises an exception.37    """38    from . import Flask3940    # Search for the most common names first.41    for attr_name in ("app", "application"):42        app = getattr(module, attr_name, None)4344        if isinstance(app, Flask):45            return app4647    # Otherwise find the only object that is a Flask instance.48    matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]4950    if len(matches) == 1:51        return matches[0]52    elif len(matches) > 1:53        raise NoAppException(54            "Detected multiple Flask applications in module"55            f" '{module.__name__}'. Use '{module.__name__}:name'"56            " to specify the correct one."57        )5859    # Search for app factory functions.60    for attr_name in ("create_app", "make_app"):61        app_factory = getattr(module, attr_name, None)6263        if inspect.isfunction(app_factory):64            try:65                app = app_factory()6667                if isinstance(app, Flask):68                    return app69            except TypeError as e:70                if not _called_with_wrong_args(app_factory):71                    raise7273                raise NoAppException(74                    f"Detected factory '{attr_name}' in module '{module.__name__}',"75                    " but could not call it without arguments. Use"76                    f" '{module.__name__}:{attr_name}(args)'"77                    " to specify arguments."78                ) from e7980    raise NoAppException(81        "Failed to find Flask application or factory in module"82        f" '{module.__name__}'. Use '{module.__name__}:name'"83        " to specify one."84    )858687def _called_with_wrong_args(f):88    """Check whether calling a function raised a ``TypeError`` because89    the call failed or because something in the factory raised the90    error.9192    :param f: The function that was called.93    :return: ``True`` if the call failed.94    """95    tb = sys.exc_info()[2]9697    try:98        while tb is not None:99            if tb.tb_frame.f_code is f.__code__:100                # In the function, it was called successfully.101                return False102103            tb = tb.tb_next104105        # Didn't reach the function.106        return True107    finally:108        # Delete tb to break a circular reference.109        # https://docs.python.org/2/library/sys.html#sys.exc_info110        del tb111112113def find_app_by_string(module, app_name):114    """Check if the given string is a variable name or a function. Call115    a function to get the app instance, or return the variable directly.116    """117    from . import Flask118119    # Parse app_name as a single expression to determine if it's a valid120    # attribute name or function call.121    try:122        expr = ast.parse(app_name.strip(), mode="eval").body123    except SyntaxError:124        raise NoAppException(125            f"Failed to parse {app_name!r} as an attribute name or function call."126        ) from None127128    if isinstance(expr, ast.Name):129        name = expr.id130        args = []131        kwargs = {}132    elif isinstance(expr, ast.Call):133        # Ensure the function name is an attribute name only.134        if not isinstance(expr.func, ast.Name):135            raise NoAppException(136                f"Function reference must be a simple name: {app_name!r}."137            )138139        name = expr.func.id140141        # Parse the positional and keyword arguments as literals.142        try:143            args = [ast.literal_eval(arg) for arg in expr.args]144            kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}145        except ValueError:146            # literal_eval gives cryptic error messages, show a generic147            # message with the full expression instead.148            raise NoAppException(149                f"Failed to parse arguments as literal values: {app_name!r}."150            ) from None151    else:152        raise NoAppException(153            f"Failed to parse {app_name!r} as an attribute name or function call."154        )155156    try:157        attr = getattr(module, name)158    except AttributeError as e:159        raise NoAppException(160            f"Failed to find attribute {name!r} in {module.__name__!r}."161        ) from e162163    # If the attribute is a function, call it with any args and kwargs164    # to get the real application.165    if inspect.isfunction(attr):166        try:167            app = attr(*args, **kwargs)168        except TypeError as e:169            if not _called_with_wrong_args(attr):170                raise171172            raise NoAppException(173                f"The factory {app_name!r} in module"174                f" {module.__name__!r} could not be called with the"175                " specified arguments."176            ) from e177    else:178        app = attr179180    if isinstance(app, Flask):181        return app182183    raise NoAppException(184        "A valid Flask application was not obtained from"185        f" '{module.__name__}:{app_name}'."186    )187188189def prepare_import(path):190    """Given a filename this will try to calculate the python path, add it191    to the search path and return the actual module name that is expected.192    """193    path = os.path.realpath(path)194195    fname, ext = os.path.splitext(path)196    if ext == ".py":197        path = fname198199    if os.path.basename(path) == "__init__":200        path = os.path.dirname(path)201202    module_name = []203204    # move up until outside package structure (no __init__.py)205    while True:206        path, name = os.path.split(path)207        module_name.append(name)208209        if not os.path.exists(os.path.join(path, "__init__.py")):210            break211212    if sys.path[0] != path:213        sys.path.insert(0, path)214215    return ".".join(module_name[::-1])216217218def locate_app(module_name, app_name, raise_if_not_found=True):219    __traceback_hide__ = True  # noqa: F841220221    try:222        __import__(module_name)223    except ImportError:224        # Reraise the ImportError if it occurred within the imported module.225        # Determine this by checking whether the trace has a depth > 1.226        if sys.exc_info()[2].tb_next:227            raise NoAppException(228                f"While importing {module_name!r}, an ImportError was"229                f" raised:\n\n{traceback.format_exc()}"230            ) from None231        elif raise_if_not_found:232            raise NoAppException(f"Could not import {module_name!r}.") from None233        else:234            return235236    module = sys.modules[module_name]237238    if app_name is None:239        return find_best_app(module)240    else:241        return find_app_by_string(module, app_name)242243244def get_version(ctx, param, value):245    if not value or ctx.resilient_parsing:246        return247248    import werkzeug249    from . import __version__250251    click.echo(252        f"Python {platform.python_version()}\n"253        f"Flask {__version__}\n"254        f"Werkzeug {werkzeug.__version__}",255        color=ctx.color,256    )257    ctx.exit()258259260version_option = click.Option(261    ["--version"],262    help="Show the Flask version.",263    expose_value=False,264    callback=get_version,265    is_flag=True,266    is_eager=True,267)268269270class DispatchingApp:271    """Special application that dispatches to a Flask application which272    is imported by name in a background thread.  If an error happens273    it is recorded and shown as part of the WSGI handling which in case274    of the Werkzeug debugger means that it shows up in the browser.275    """276277    def __init__(self, loader, use_eager_loading=None):278        self.loader = loader279        self._app = None280        self._lock = Lock()281        self._bg_loading_exc = None282283        if use_eager_loading is None:284            use_eager_loading = not is_running_from_reloader()285286        if use_eager_loading:287            self._load_unlocked()288        else:289            self._load_in_background()290291    def _load_in_background(self):292        # Store the Click context and push it in the loader thread so293        # script_info is still available.294        ctx = click.get_current_context(silent=True)295296        def _load_app():297            __traceback_hide__ = True  # noqa: F841298299            with self._lock:300                if ctx is not None:301                    click.globals.push_context(ctx)302303                try:304                    self._load_unlocked()305                except Exception as e:306                    self._bg_loading_exc = e307308        t = Thread(target=_load_app, args=())309        t.start()310311    def _flush_bg_loading_exception(self):312        __traceback_hide__ = True  # noqa: F841313        exc = self._bg_loading_exc314315        if exc is not None:316            self._bg_loading_exc = None317            raise exc318319    def _load_unlocked(self):320        __traceback_hide__ = True  # noqa: F841321        self._app = rv = self.loader()322        self._bg_loading_exc = None323        return rv324325    def __call__(self, environ, start_response):326        __traceback_hide__ = True  # noqa: F841327        if self._app is not None:328            return self._app(environ, start_response)329        self._flush_bg_loading_exception()330        with self._lock:331            if self._app is not None:332                rv = self._app333            else:334                rv = self._load_unlocked()335            return rv(environ, start_response)336337338class ScriptInfo:339    """Helper object to deal with Flask applications.  This is usually not340    necessary to interface with as it's used internally in the dispatching341    to click.  In future versions of Flask this object will most likely play342    a bigger role.  Typically it's created automatically by the343    :class:`FlaskGroup` but you can also manually create it and pass it344    onwards as click object.345    """346347    def __init__(348        self,349        app_import_path: str | None = None,350        create_app: t.Callable[..., Flask] | None = None,351        set_debug_flag: bool = True,352    ) -> None:353        #: Optionally the import path for the Flask application.354        self.app_import_path = app_import_path355        #: Optionally a function that is passed the script info to create356        #: the instance of the application.357        self.create_app = create_app358        #: A dictionary with arbitrary data that can be associated with359        #: this script info.360        self.data: t.Dict[t.Any, t.Any] = {}361        self.set_debug_flag = set_debug_flag362        self._loaded_app: Flask | None = None363364    def load_app(self) -> Flask:365        """Loads the Flask app (if not yet loaded) and returns it.  Calling366        this multiple times will just result in the already loaded app to367        be returned.368        """369        __traceback_hide__ = True  # noqa: F841370371        if self._loaded_app is not None:372            return self._loaded_app373374        if self.create_app is not None:375            app = self.create_app()376        else:377            if self.app_import_path:378                path, name = (379                    re.split(r":(?![\\/])", self.app_import_path, 1) + [None]380                )[:2]381                import_name = prepare_import(path)382                app = locate_app(import_name, name)383            else:384                for path in ("wsgi.py", "app.py"):385                    import_name = prepare_import(path)386                    app = locate_app(import_name, None, raise_if_not_found=False)387388                    if app:389                        break390391        if not app:392            raise NoAppException(393                "Could not locate a Flask application. Use the"394                " 'flask --app' option, 'FLASK_APP' environment"395                " variable, or a 'wsgi.py' or 'app.py' file in the"396                " current directory."397            )398399        if self.set_debug_flag:400            # Update the app's debug flag through the descriptor so that401            # other values repopulate as well.402            app.debug = get_debug_flag()403404        self._loaded_app = app405        return app406407408pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)409410411def with_appcontext(f):412    """Wraps a callback so that it's guaranteed to be executed with the413    script's application context.414415    Custom commands (and their options) registered under ``app.cli`` or416    ``blueprint.cli`` will always have an app context available, this417    decorator is not required in that case.418419    .. versionchanged:: 2.2420        The app context is active for subcommands as well as the421        decorated callback. The app context is always available to422        ``app.cli`` command and parameter callbacks.423    """424425    @click.pass_context426    def decorator(__ctx, *args, **kwargs):427        if not current_app:428            app = __ctx.ensure_object(ScriptInfo).load_app()429            __ctx.with_resource(app.app_context())430431        return __ctx.invoke(f, *args, **kwargs)432433    return update_wrapper(decorator, f)434435436class AppGroup(click.Group):437    """This works similar to a regular click :class:`~click.Group` but it438    changes the behavior of the :meth:`command` decorator so that it439    automatically wraps the functions in :func:`with_appcontext`.440441    Not to be confused with :class:`FlaskGroup`.442    """443444    def command(self, *args, **kwargs):445        """This works exactly like the method of the same name on a regular446        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`447        unless it's disabled by passing ``with_appcontext=False``.448        """449        wrap_for_ctx = kwargs.pop("with_appcontext", True)450451        def decorator(f):452            if wrap_for_ctx:453                f = with_appcontext(f)454            return click.Group.command(self, *args, **kwargs)(f)455456        return decorator457458    def group(self, *args, **kwargs):459        """This works exactly like the method of the same name on a regular460        :class:`click.Group` but it defaults the group class to461        :class:`AppGroup`.462        """463        kwargs.setdefault("cls", AppGroup)464        return click.Group.group(self, *args, **kwargs)465466467def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:468    if value is None:469        return None470471    info = ctx.ensure_object(ScriptInfo)472    info.app_import_path = value473    return value474475476# This option is eager so the app will be available if --help is given.477# --help is also eager, so --app must be before it in the param list.478# no_args_is_help bypasses eager processing, so this option must be479# processed manually in that case to ensure FLASK_APP gets picked up.480_app_option = click.Option(481    ["-A", "--app"],482    metavar="IMPORT",483    help=(484        "The Flask application or factory function to load, in the form 'module:name'."485        " Module can be a dotted import or file path. Name is not required if it is"486        " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"487        " pass arguments."488    ),489    is_eager=True,490    expose_value=False,491    callback=_set_app,492)493494495def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:496    if value is None:497        return None498499    # Set with env var instead of ScriptInfo.load so that it can be500    # accessed early during a factory function.501    os.environ["FLASK_ENV"] = value502    return value503504505_env_option = click.Option(506    ["-E", "--env"],507    metavar="NAME",508    help=(509        "The execution environment name to set in 'app.env'. Defaults to"510        " 'production'. 'development' will enable 'app.debug' and start the"511        " debugger and reloader when running the server."512    ),513    expose_value=False,514    callback=_set_env,515)516517518def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:519    # If the flag isn't provided, it will default to False. Don't use520    # that, let debug be set by env in that case.521    source = ctx.get_parameter_source(param.name)  # type: ignore[arg-type]522523    if source is not None and source in (524        ParameterSource.DEFAULT,525        ParameterSource.DEFAULT_MAP,526    ):527        return None528529    # Set with env var instead of ScriptInfo.load so that it can be530    # accessed early during a factory function.531    os.environ["FLASK_DEBUG"] = "1" if value else "0"532    return value533534535_debug_option = click.Option(536    ["--debug/--no-debug"],537    help="Set 'app.debug' separately from '--env'.",538    expose_value=False,539    callback=_set_debug,540)541542543def _env_file_callback(544    ctx: click.Context, param: click.Option, value: str | None545) -> str | None:546    if value is None:547        return None548549    import importlib550551    try:552        importlib.import_module("dotenv")553    except ImportError:554        raise click.BadParameter(555            "python-dotenv must be installed to load an env file.",556            ctx=ctx,557            param=param,558        ) from None559560    # Don't check FLASK_SKIP_DOTENV, that only disables automatically561    # loading .env and .flaskenv files.562    load_dotenv(value)563    return value564565566# This option is eager so env vars are loaded as early as possible to be567# used by other options.568_env_file_option = click.Option(569    ["-e", "--env-file"],570    type=click.Path(exists=True, dir_okay=False),571    help="Load environment variables from this file. python-dotenv must be installed.",572    is_eager=True,573    expose_value=False,574    callback=_env_file_callback,575)576577578class FlaskGroup(AppGroup):579    """Special subclass of the :class:`AppGroup` group that supports580    loading more commands from the configured Flask app.  Normally a581    developer does not have to interface with this class but there are582    some very advanced use cases for which it makes sense to create an583    instance of this. see :ref:`custom-scripts`.584585    :param add_default_commands: if this is True then the default run and586        shell commands will be added.587    :param add_version_option: adds the ``--version`` option.588    :param create_app: an optional callback that is passed the script info and589        returns the loaded app.590    :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`591        files to set environment variables. Will also change the working592        directory to the directory containing the first file found.593    :param set_debug_flag: Set the app's debug flag based on the active594        environment595596    .. versionchanged:: 2.2597        Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,598        and ``-e/--env-file`` options.599600    .. versionchanged:: 2.2601        An app context is pushed when running ``app.cli`` commands, so602        ``@with_appcontext`` is no longer required for those commands.603604    .. versionchanged:: 1.0605        If installed, python-dotenv will be used to load environment variables606        from :file:`.env` and :file:`.flaskenv` files.607    """608609    def __init__(610        self,611        add_default_commands: bool = True,612        create_app: t.Callable[..., Flask] | None = None,613        add_version_option: bool = True,614        load_dotenv: bool = True,615        set_debug_flag: bool = True,616        **extra: t.Any,617    ) -> None:618        params = list(extra.pop("params", None) or ())619        # Processing is done with option callbacks instead of a group620        # callback. This allows users to make a custom group callback621        # without losing the behavior. --env-file must come first so622        # that it is eagerly evaluated before --app.623        params.extend((_env_file_option, _app_option, _env_option, _debug_option))624625        if add_version_option:626            params.append(version_option)627628        if "context_settings" not in extra:629            extra["context_settings"] = {}630631        extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")632633        super().__init__(params=params, **extra)634635        self.create_app = create_app636        self.load_dotenv = load_dotenv637        self.set_debug_flag = set_debug_flag638639        if add_default_commands:640            self.add_command(run_command)641            self.add_command(shell_command)642            self.add_command(routes_command)643644        self._loaded_plugin_commands = False645646    def _load_plugin_commands(self):647        if self._loaded_plugin_commands:648            return649650        if sys.version_info >= (3, 10):651            from importlib import metadata652        else:653            # Use a backport on Python < 3.10. We technically have654            # importlib.metadata on 3.8+, but the API changed in 3.10,655            # so use the backport for consistency.656            import importlib_metadata as metadata657658        for ep in metadata.entry_points(group="flask.commands"):659            self.add_command(ep.load(), ep.name)660661        self._loaded_plugin_commands = True662663    def get_command(self, ctx, name):664        self._load_plugin_commands()665        # Look up built-in and plugin commands, which should be666        # available even if the app fails to load.667        rv = super().get_command(ctx, name)668669        if rv is not None:670            return rv671672        info = ctx.ensure_object(ScriptInfo)673674        # Look up commands provided by the app, showing an error and675        # continuing if the app couldn't be loaded.676        try:677            app = info.load_app()678        except NoAppException as e:679            click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")680            return None681682        # Push an app context for the loaded app unless it is already683        # active somehow. This makes the context available to parameter684        # and command callbacks without needing @with_appcontext.685        if not current_app or current_app._get_current_object() is not app:686            ctx.with_resource(app.app_context())687688        return app.cli.get_command(ctx, name)689690    def list_commands(self, ctx):691        self._load_plugin_commands()692        # Start with the built-in and plugin commands.693        rv = set(super().list_commands(ctx))694        info = ctx.ensure_object(ScriptInfo)695696        # Add commands provided by the app, showing an error and697        # continuing if the app couldn't be loaded.698        try:699            rv.update(info.load_app().cli.list_commands(ctx))700        except NoAppException as e:701            # When an app couldn't be loaded, show the error message702            # without the traceback.703            click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")704        except Exception:705            # When any other errors occurred during loading, show the706            # full traceback.707            click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")708709        return sorted(rv)710711    def make_context(712        self,713        info_name: str | None,714        args: list[str],715        parent: click.Context | None = None,716        **extra: t.Any,717    ) -> click.Context:718        # Set a flag to tell app.run to become a no-op. If app.run was719        # not in a __name__ == __main__ guard, it would start the server720        # when importing, blocking whatever command is being called.721        os.environ["FLASK_RUN_FROM_CLI"] = "true"722723        # Attempt to load .env and .flask env files. The --env-file724        # option can cause another file to be loaded.725        if get_load_dotenv(self.load_dotenv):726            load_dotenv()727728        if "obj" not in extra and "obj" not in self.context_settings:729            extra["obj"] = ScriptInfo(730                create_app=self.create_app, set_debug_flag=self.set_debug_flag731            )732733        return super().make_context(info_name, args, parent=parent, **extra)734735    def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:736        if not args and self.no_args_is_help:737            # Attempt to load --env-file and --app early in case they738            # were given as env vars. Otherwise no_args_is_help will not739            # see commands from app.cli.740            _env_file_option.handle_parse_result(ctx, {}, [])741            _app_option.handle_parse_result(ctx, {}, [])742743        return super().parse_args(ctx, args)744745746def _path_is_ancestor(path, other):747    """Take ``other`` and remove the length of ``path`` from it. Then join it748    to ``path``. If it is the original value, ``path`` is an ancestor of749    ``other``."""750    return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other751752753def load_dotenv(path: str | os.PathLike | None = None) -> bool:754    """Load "dotenv" files in order of precedence to set environment variables.755756    If an env var is already set it is not overwritten, so earlier files in the757    list are preferred over later files.758759    This is a no-op if `python-dotenv`_ is not installed.760761    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme762763    :param path: Load the file at this location instead of searching.764    :return: ``True`` if a file was loaded.765766    .. versionchanged:: 2.0767        The current directory is not changed to the location of the768        loaded file.769770    .. versionchanged:: 2.0771        When loading the env files, set the default encoding to UTF-8.772773    .. versionchanged:: 1.1.0774        Returns ``False`` when python-dotenv is not installed, or when775        the given path isn't a file.776777    .. versionadded:: 1.0778    """779    try:780        import dotenv781    except ImportError:782        if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):783            click.secho(784                " * Tip: There are .env or .flaskenv files present."785                ' Do "pip install python-dotenv" to use them.',786                fg="yellow",787                err=True,788            )789790        return False791792    # Always return after attempting to load a given path, don't load793    # the default files.794    if path is not None:795        if os.path.isfile(path):796            return dotenv.load_dotenv(path, encoding="utf-8")797798        return False799800    loaded = False801802    for name in (".env", ".flaskenv"):803        path = dotenv.find_dotenv(name, usecwd=True)804805        if not path:806            continue807808        dotenv.load_dotenv(path, encoding="utf-8")809        loaded = True810811    return loaded  # True if at least one file was located and loaded.812813814def show_server_banner(env, debug, app_import_path, eager_loading):815    """Show extra startup messages the first time the server is run,816    ignoring the reloader.817    """818    if is_running_from_reloader():819        return820821    if app_import_path is not None:822        message = f" * Serving Flask app {app_import_path!r}"823824        if not eager_loading:825            message += " (lazy loading)"826827        click.echo(message)828829    click.echo(f" * Environment: {env}")830831    if env == "production":832        click.secho(833            "   WARNING: This is a development server. Do not use it in"834            " a production deployment.\n   Use a production WSGI server"835            " instead.",836            fg="red",837        )838839    if debug is not None:840        click.echo(f" * Debug mode: {'on' if debug else 'off'}")841842843class CertParamType(click.ParamType):844    """Click option type for the ``--cert`` option. Allows either an845    existing file, the string ``'adhoc'``, or an import for a846    :class:`~ssl.SSLContext` object.847    """848849    name = "path"850851    def __init__(self):852        self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)853854    def convert(self, value, param, ctx):855        try:856            import ssl857        except ImportError:858            raise click.BadParameter(859                'Using "--cert" requires Python to be compiled with SSL support.',860                ctx,861                param,862            ) from None863864        try:865            return self.path_type(value, param, ctx)866        except click.BadParameter:867            value = click.STRING(value, param, ctx).lower()868869            if value == "adhoc":870                try:871                    import cryptography  # noqa: F401872                except ImportError:873                    raise click.BadParameter(874                        "Using ad-hoc certificates requires the cryptography library.",875                        ctx,876                        param,877                    ) from None878879                return value880881            obj = import_string(value, silent=True)882883            if isinstance(obj, ssl.SSLContext):884                return obj885886            raise887888889def _validate_key(ctx, param, value):890    """The ``--key`` option must be specified when ``--cert`` is a file.891    Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.892    """893    cert = ctx.params.get("cert")894    is_adhoc = cert == "adhoc"895896    try:897        import ssl898    except ImportError:899        is_context = False900    else:901        is_context = isinstance(cert, ssl.SSLContext)902903    if value is not None:904        if is_adhoc:905            raise click.BadParameter(906                'When "--cert" is "adhoc", "--key" is not used.', ctx, param907            )908909        if is_context:910            raise click.BadParameter(911                'When "--cert" is an SSLContext object, "--key is not used.', ctx, param912            )913914        if not cert:915            raise click.BadParameter('"--cert" must also be specified.', ctx, param)916917        ctx.params["cert"] = cert, value918919    else:920        if cert and not (is_adhoc or is_context):921            raise click.BadParameter('Required when using "--cert".', ctx, param)922923    return value924925926class SeparatedPathType(click.Path):927    """Click option type that accepts a list of values separated by the928    OS's path separator (``:``, ``;`` on Windows). Each value is929    validated as a :class:`click.Path` type.930    """931932    def convert(self, value, param, ctx):933        items = self.split_envvar_value(value)934        super_convert = super().convert935        return [super_convert(item, param, ctx) for item in items]936937938@click.command("run", short_help="Run a development server.")939@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")940@click.option("--port", "-p", default=5000, help="The port to bind to.")941@click.option(942    "--cert",943    type=CertParamType(),944    help="Specify a certificate file to use HTTPS.",945    is_eager=True,946)947@click.option(948    "--key",949    type=click.Path(exists=True, dir_okay=False, resolve_path=True),950    callback=_validate_key,951    expose_value=False,952    help="The key file to use when specifying a certificate.",953)954@click.option(955    "--reload/--no-reload",956    default=None,957    help="Enable or disable the reloader. By default the reloader "958    "is active if debug is enabled.",959)960@click.option(961    "--debugger/--no-debugger",962    default=None,963    help="Enable or disable the debugger. By default the debugger "964    "is active if debug is enabled.",965)966@click.option(967    "--eager-loading/--lazy-loading",968    default=None,969    help="Enable or disable eager loading. By default eager "970    "loading is enabled if the reloader is disabled.",971)972@click.option(973    "--with-threads/--without-threads",974    default=True,975    help="Enable or disable multithreading.",976)977@click.option(978    "--extra-files",979    default=None,980    type=SeparatedPathType(),981    help=(982        "Extra files that trigger a reload on change. Multiple paths"983        f" are separated by {os.path.pathsep!r}."984    ),985)986@click.option(987    "--exclude-patterns",988    default=None,989    type=SeparatedPathType(),990    help=(991        "Files matching these fnmatch patterns will not trigger a reload"992        " on change. Multiple patterns are separated by"993        f" {os.path.pathsep!r}."994    ),995)996@pass_script_info997def run_command(998    info,999    host,1000    port,1001    reload,1002    debugger,1003    eager_loading,1004    with_threads,1005    cert,1006    extra_files,1007    exclude_patterns,1008):1009    """Run a local development server.10101011    This server is for development purposes only. It does not provide1012    the stability, security, or performance of production WSGI servers.10131014    The reloader and debugger are enabled by default with the1015    '--env development' or '--debug' options.1016    """1017    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)1018    debug = get_debug_flag()10191020    if reload is None:1021        reload = debug10221023    if debugger is None:1024        debugger = debug10251026    show_server_banner(get_env(), debug, info.app_import_path, eager_loading)10271028    from werkzeug.serving import run_simple10291030    run_simple(1031        host,1032        port,1033        app,1034        use_reloader=reload,1035        use_debugger=debugger,1036        threaded=with_threads,1037        ssl_context=cert,1038        extra_files=extra_files,1039        exclude_patterns=exclude_patterns,1040    )104110421043@click.command("shell", short_help="Run a shell in the app context.")1044@with_appcontext1045def shell_command() -> None:1046    """Run an interactive Python shell in the context of a given1047    Flask application.  The application will populate the default1048    namespace of this shell according to its configuration.10491050    This is useful for executing small snippets of management code1051    without having to manually configure the application.1052    """1053    import code10541055    banner = (1056        f"Python {sys.version} on {sys.platform}\n"1057        f"App: {current_app.import_name} [{current_app.env}]\n"1058        f"Instance: {current_app.instance_path}"1059    )1060    ctx: dict = {}10611062    # Support the regular Python interpreter startup script if someone1063    # is using it.1064    startup = os.environ.get("PYTHONSTARTUP")1065    if startup and os.path.isfile(startup):1066        with open(startup) as f:1067            eval(compile(f.read(), startup, "exec"), ctx)10681069    ctx.update(current_app.make_shell_context())10701071    # Site, customize, or startup script can set a hook to call when1072    # entering interactive mode. The default one sets up readline with1073    # tab and history completion.1074    interactive_hook = getattr(sys, "__interactivehook__", None)10751076    if interactive_hook is not None:1077        try:1078            import readline1079            from rlcompleter import Completer1080        except ImportError:1081            pass1082        else:1083            # rlcompleter uses __main__.__dict__ by default, which is1084            # flask.__main__. Use the shell context instead.1085            readline.set_completer(Completer(ctx).complete)10861087        interactive_hook()10881089    code.interact(banner=banner, local=ctx)109010911092@click.command("routes", short_help="Show the routes for the app.")1093@click.option(1094    "--sort",1095    "-s",1096    type=click.Choice(("endpoint", "methods", "rule", "match")),1097    default="endpoint",1098    help=(1099        'Method to sort routes by. "match" is the order that Flask will match '1100        "routes when dispatching a request."1101    ),1102)1103@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")1104@with_appcontext1105def routes_command(sort: str, all_methods: bool) -> None:1106    """Show all registered routes with endpoints and methods."""11071108    rules = list(current_app.url_map.iter_rules())1109    if not rules:1110        click.echo("No routes were registered.")1111        return11121113    ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))11141115    if sort in ("endpoint", "rule"):1116        rules = sorted(rules, key=attrgetter(sort))1117    elif sort == "methods":1118        rules = sorted(rules, key=lambda rule: sorted(rule.methods))  # type: ignore11191120    rule_methods = [1121        ", ".join(sorted(rule.methods - ignored_methods))  # type: ignore1122        for rule in rules1123    ]11241125    headers = ("Endpoint", "Methods", "Rule")1126    widths = (1127        max(len(rule.endpoint) for rule in rules),1128        max(len(methods) for methods in rule_methods),1129        max(len(rule.rule) for rule in rules),1130    )1131    widths = [max(len(h), w) for h, w in zip(headers, widths)]1132    row = "{{0:<{0}}}  {{1:<{1}}}  {{2:<{2}}}".format(*widths)11331134    click.echo(row.format(*headers).strip())1135    click.echo(row.format(*("-" * width for width in widths)))11361137    for rule, methods in zip(rules, rule_methods):1138        click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())113911401141cli = FlaskGroup(1142    name="flask",1143    help="""\1144A general utility script for Flask applications.11451146An application to load must be given with the '--app' option,1147'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file1148in the current directory.1149""",1150)115111521153def main() -> None:1154    cli.main()115511561157if __name__ == "__main__":1158    main()