add --app, --env, --debug, and --env-file CLI options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent fe4003b · Browse files · 3 files·+197 added−54 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+197 added−54 removed
- other:+197 added−54 removed
Provenance
- Commit
99fa3c3- Tree
21ae9cb- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
fe4003b
3 files changed+197 added−54 removed
modified:src/flask/cli.py+188 added-51 removed
1+from __future__ import annotations2+3 import ast4 import inspect5 import os6 import platform6 unmodified lines13 from threading import Lock14 from threading import Thread15 16 import click17+from click.core import ParameterSource18 from werkzeug.serving import is_running_from_reloader19 from werkzeug.utils import import_string20 21 from .globals import current_app22 from .helpers import get_debug_flag23 from .helpers import get_env24 from .helpers import get_load_dotenv25 26+if t.TYPE_CHECKING:27+ from .app import Flask28 29+30 class NoAppException(click.UsageError):31 """Raised if an application cannot be found or loaded."""32 33 17 unmodified lines51 return matches[0]52 elif len(matches) > 1:53 raise NoAppException(54 "Detected multiple Flask applications in module"49- f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"50- f" to specify the correct one."55+ f" '{module.__name__}'. Use '{module.__name__}:name'"56+ " to specify the correct one."57 )58 59 # Search for app factory functions.60 for attr_name in ("create_app", "make_app"):9 unmodified lines70 if not _called_with_wrong_args(app_factory):71 raise72 73 raise NoAppException(68- f"Detected factory {attr_name!r} in module {module.__name__!r},"74+ f"Detected factory '{attr_name}' in module '{module.__name__}',"75 " but could not call it without arguments. Use"70- f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""76+ f" '{module.__name__}:{attr_name}(args)'"77 " to specify arguments."78 ) from e79 80 raise NoAppException(81 "Failed to find Flask application or factory in module"76- f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"82+ f" '{module.__name__}'. Use '{module.__name__}:name'"83 " to specify one."84 )85 86 171 unmodified lines258 259 260 version_option = click.Option(261 ["--version"],256- help="Show the flask version",262+ help="Show the Flask version.",263 expose_value=False,264 callback=get_version,265 is_flag=True,266 is_eager=True,76 unmodified lines343 :class:`FlaskGroup` but you can also manually create it and pass it344 onwards as click object.345 """346 341- def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):347+ 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.343- self.app_import_path = app_import_path or os.environ.get("FLASK_APP")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.349- self.data = {}360+ self.data: t.Dict[t.Any, t.Any] = {}361 self.set_debug_flag = set_debug_flag351- self._loaded_app = None362+ self._loaded_app: Flask | None = None363 353- def load_app(self):364+ 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 """20 unmodified lines389 break390 391 if not app:392 raise NoAppException(382- "Could not locate a Flask application. You did not provide "383- 'the "FLASK_APP" environment variable, and a "wsgi.py" or '384- '"app.py" module was not found in the current directory.'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 )398 399 if self.set_debug_flag:400 # Update the app's debug flag through the descriptor so that52 unmodified lines453 kwargs.setdefault("cls", AppGroup)454 return click.Group.group(self, *args, **kwargs)455 456 457+def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:458+ if value is None:459+ return None460+461+ info = ctx.ensure_object(ScriptInfo)462+ info.app_import_path = value463+ return value464+465+466+# This option is eager so the app will be available if --help is given.467+# --help is also eager, so --app must be before it in the param list.468+# no_args_is_help bypasses eager processing, so this option must be469+# processed manually in that case to ensure FLASK_APP gets picked up.470+_app_option = click.Option(471+ ["-A", "--app"],472+ metavar="IMPORT",473+ help=(474+ "The Flask application or factory function to load, in the form 'module:name'."475+ " Module can be a dotted import or file path. Name is not required if it is"476+ " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"477+ " pass arguments."478+ ),479+ is_eager=True,480+ expose_value=False,481+ callback=_set_app,482+)483+484+485+def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:486+ if value is None:487+ return None488+489+ # Set with env var instead of ScriptInfo.load so that it can be490+ # accessed early during a factory function.491+ os.environ["FLASK_ENV"] = value492+ return value493+494+495+_env_option = click.Option(496+ ["-E", "--env"],497+ metavar="NAME",498+ help=(499+ "The execution environment name to set in 'app.env'. Defaults to"500+ " 'production'. 'development' will enable 'app.debug' and start the"501+ " debugger and reloader when running the server."502+ ),503+ expose_value=False,504+ callback=_set_env,505+)506+507+508+def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:509+ # If the flag isn't provided, it will default to False. Don't use510+ # that, let debug be set by env in that case.511+ source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]512+513+ if source is not None and source in (514+ ParameterSource.DEFAULT,515+ ParameterSource.DEFAULT_MAP,516+ ):517+ return None518+519+ # Set with env var instead of ScriptInfo.load so that it can be520+ # accessed early during a factory function.521+ os.environ["FLASK_DEBUG"] = "1" if value else "0"522+ return value523+524+525+_debug_option = click.Option(526+ ["--debug/--no-debug"],527+ help="Set 'app.debug' separately from '--env'.",528+ expose_value=False,529+ callback=_set_debug,530+)531+532+533+def _env_file_callback(534+ ctx: click.Context, param: click.Option, value: str | None535+) -> str | None:536+ if value is None:537+ return None538+539+ import importlib540+541+ try:542+ importlib.import_module("dotenv")543+ except ImportError:544+ raise click.BadParameter(545+ "python-dotenv must be installed to load an env file.",546+ ctx=ctx,547+ param=param,548+ ) from None549+550+ # Don't check FLASK_SKIP_DOTENV, that only disables automatically551+ # loading .env and .flaskenv files.552+ load_dotenv(value)553+ return value554+555+556+# This option is eager so env vars are loaded as early as possible to be557+# used by other options.558+_env_file_option = click.Option(559+ ["-e", "--env-file"],560+ type=click.Path(exists=True, dir_okay=False),561+ help="Load environment variables from this file. python-dotenv must be installed.",562+ is_eager=True,563+ expose_value=False,564+ callback=_env_file_callback,565+)566+567+568 class FlaskGroup(AppGroup):569 """Special subclass of the :class:`AppGroup` group that supports570 loading more commands from the configured Flask app. Normally a571 developer does not have to interface with this class but there are10 unmodified lines582 directory to the directory containing the first file found.583 :param set_debug_flag: Set the app's debug flag based on the active584 environment585 586+ .. versionchanged:: 2.2587+ Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,588+ and ``-e/--env-file`` options.589+590 .. versionchanged:: 1.0591 If installed, python-dotenv will be used to load environment variables592 from :file:`.env` and :file:`.flaskenv` files.593 """594 595 def __init__(596 self,470- add_default_commands=True,471- create_app=None,472- add_version_option=True,473- load_dotenv=True,474- set_debug_flag=True,475- **extra,476- ):597+ add_default_commands: bool = True,598+ create_app: t.Callable[..., Flask] | None = None,599+ add_version_option: bool = True,600+ load_dotenv: bool = True,601+ set_debug_flag: bool = True,602+ **extra: t.Any,603+ ) -> None:604 params = list(extra.pop("params", None) or ())605+ # Processing is done with option callbacks instead of a group606+ # callback. This allows users to make a custom group callback607+ # without losing the behavior. --env-file must come first so608+ # that it is eagerly evaluated before --app.609+ params.extend((_env_file_option, _app_option, _env_option, _debug_option))610 611 if add_version_option:612 params.append(version_option)613 72 unmodified lines686 return sorted(rv)687 688 def make_context(689 self,558- info_name: t.Optional[str],559- args: t.List[str],560- parent: t.Optional[click.Context] = None,690+ info_name: str | None,691+ args: list[str],692+ parent: click.Context | None = None,693 **extra: t.Any,694 ) -> click.Context:695+ # Attempt to load .env and .flask env files. The --env-file696+ # option can cause another file to be loaded.697 if get_load_dotenv(self.load_dotenv):698 load_dotenv()699 700 if "obj" not in extra and "obj" not in self.context_settings:2 unmodified lines703 )704 705 return super().make_context(info_name, args, parent=parent, **extra)706 707+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:708+ if not args and self.no_args_is_help:709+ # Attempt to load --env-file and --app early in case they710+ # were given as env vars. Otherwise no_args_is_help will not711+ # see commands from app.cli.712+ _env_file_option.handle_parse_result(ctx, {}, [])713+ _app_option.handle_parse_result(ctx, {}, [])714 715+ return super().parse_args(ctx, args)716+717+718 def _path_is_ancestor(path, other):719 """Take ``other`` and remove the length of ``path`` from it. Then join it720 to ``path``. If it is the original value, ``path`` is an ancestor of721 ``other``."""722 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other723 724 581-def load_dotenv(path=None):725+def load_dotenv(path: str | os.PathLike | None = None) -> bool:726 """Load "dotenv" files in order of precedence to set environment variables.727 728 If an env var is already set it is not overwritten, so earlier files in the729 list are preferred over later files.4 unmodified lines734 735 :param path: Load the file at this location instead of searching.736 :return: ``True`` if a file was loaded.737 594- .. versionchanged:: 1.1.0595- Returns ``False`` when python-dotenv is not installed, or when596- the given path isn't a file.738+ .. versionchanged:: 2.0739+ The current directory is not changed to the location of the740+ loaded file.741 742 .. versionchanged:: 2.0743 When loading the env files, set the default encoding to UTF-8.744 745+ .. versionchanged:: 1.1.0746+ Returns ``False`` when python-dotenv is not installed, or when747+ the given path isn't a file.748+749 .. versionadded:: 1.0750 """751 try:752 import dotenv7 unmodified lines760 )761 762 return False763 616- # if the given path specifies the actual file then return True,617- # else False764+ # Always return after attempting to load a given path, don't load765+ # the default files.766 if path is not None:767 if os.path.isfile(path):768 return dotenv.load_dotenv(path, encoding="utf-8")769 770 return False771 624- new_dir = None772+ loaded = False773 774 for name in (".env", ".flaskenv"):775 path = dotenv.find_dotenv(name, usecwd=True)776 777 if not path:778 continue779 632- if new_dir is None:633- new_dir = os.path.dirname(path)634-780 dotenv.load_dotenv(path, encoding="utf-8")781+ loaded = True782 637- return new_dir is not None # at least one file was located and loaded783+ return loaded # True if at least one file was located and loaded.784 785 786 def show_server_banner(env, debug, app_import_path, eager_loading):787 """Show extra startup messages the first time the server is run,194 unmodified lines982 983 This server is for development purposes only. It does not provide984 the stability, security, or performance of production WSGI servers.985 840- The reloader and debugger are enabled by default if841- FLASK_ENV=development or FLASK_DEBUG=1.986+ The reloader and debugger are enabled by default with the987+ '--env development' or '--debug' options.988 """989+ app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)990 debug = get_debug_flag()991 992 if reload is None:993 reload = debug1 unmodified line995 if debugger is None:996 debugger = debug997 998 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)852- app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)999 1000 from werkzeug.serving import run_simple1001 1002 run_simple(113 unmodified lines1116 name="flask",1117 help="""\1118 A general utility script for Flask applications.1119 974-Provides commands from Flask, extensions, and the application. Loads the975-application defined in the FLASK_APP environment variable, or from a wsgi.py976-file. Setting the FLASK_ENV environment variable to 'development' will enable977-debug mode.978-979-\b980- {prefix}{cmd} FLASK_APP=hello.py981- {prefix}{cmd} FLASK_ENV=development982- {prefix}flask run983-""".format(984- cmd="export" if os.name == "posix" else "set",985- prefix="$ " if os.name == "posix" else "> ",986- ),1120+An application to load must be given with the '--app' option,1121+'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file1122+in the current directory.1123+""",1124 )1125 1126 1127 def main() -> None:5 unmodified linesmodified:src/flask/helpers.py+3 added-3 removed
46 unmodified lines47 return val.lower() not in ("0", "false", "no")48 49 50 def get_load_dotenv(default: bool = True) -> bool:51- """Get whether the user has disabled loading dotenv files by setting52- :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load the53- files.51+ """Get whether the user has disabled loading default dotenv files by52+ setting :envvar:`FLASK_SKIP_DOTENV`. The default is ``True``, load53+ the files.54 55 :param default: What to return if the env var isn't set.56 """57 val = os.environ.get("FLASK_SKIP_DOTENV")687 unmodified linesmodified:CHANGES.rst+6 added
25 unmodified lines26 subclass sets this to ``False``, the view will not create a new27 instance on every request. :issue:`2520`.28 - A ``flask.cli.FlaskGroup`` Click group can be nested as a29 sub-command in a custom CLI. :issue:`3263`30+- Add ``--app``, ``--env``, and ``--debug`` options to the ``flask``31+ CLI, instead of requiring that they are set through environment32+ variables. :issue:`2836`33+- Add ``--env-file`` option to the ``flask`` CLI. This allows34+ specifying a dotenv file to load in addition to ``.env`` and35+ ``.flaskenv``. :issue:`3108`36 37 38 Version 2.1.339 -------------1291 unmodified lines