Skip to content
Myr

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

3 files+197 added−54 removed

modified:src/flask/cli.py+188 added-51 removed
1from __future__ import annotations23import ast4import inspect5import os6import platform
6 unmodified lines
13from 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."""3233
17 unmodified lines
51 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 )5859 # Search for app factory functions.60 for attr_name in ("create_app", "make_app"):
9 unmodified lines
70 if not _called_with_wrong_args(app_factory):71 raise7273 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 e7980 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 )8586
171 unmodified lines
258259260version_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 lines
343 :class:`FlaskGroup` but you can also manually create it and pass it344 onwards as click object.345 """346341 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 = None363353 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 lines
389 break390391 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 )398399 if self.set_debug_flag:400 # Update the app's debug flag through the descriptor so that
52 unmodified lines
453 kwargs.setdefault("cls", AppGroup)454 return click.Group.group(self, *args, **kwargs)455456457def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:458 if value is None:459 return None460461 info = ctx.ensure_object(ScriptInfo)462 info.app_import_path = value463 return value464465466# 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)483484485def _set_env(ctx: click.Context, param: click.Option, value: str | None) -> str | None:486 if value is None:487 return None488489 # 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 value493494495_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)506507508def _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]512513 if source is not None and source in (514 ParameterSource.DEFAULT,515 ParameterSource.DEFAULT_MAP,516 ):517 return None518519 # 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 value523524525_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)531532533def _env_file_callback(534 ctx: click.Context, param: click.Option, value: str | None535) -> str | None:536 if value is None:537 return None538539 import importlib540541 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 None549550 # Don't check FLASK_SKIP_DOTENV, that only disables automatically551 # loading .env and .flaskenv files.552 load_dotenv(value)553 return value554555556# 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)566567568class 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 are
10 unmodified lines
582 directory to the directory containing the first file found.583 :param set_debug_flag: Set the app's debug flag based on the active584 environment585586 .. versionchanged:: 2.2587 Added the ``-A/--app``, ``-E/--env``, ``--debug/--no-debug``,588 and ``-e/--env-file`` options.589590 .. versionchanged:: 1.0591 If installed, python-dotenv will be used to load environment variables592 from :file:`.env` and :file:`.flaskenv` files.593 """594595 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))610611 if add_version_option:612 params.append(version_option)613
72 unmodified lines
686 return sorted(rv)687688 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()699700 if "obj" not in extra and "obj" not in self.context_settings:
2 unmodified lines
703 )704705 return super().make_context(info_name, args, parent=parent, **extra)706707 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, {}, [])714715 return super().parse_args(ctx, args)716717718def _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)) == other723724581def load_dotenv(path=None):725def load_dotenv(path: str | os.PathLike | None = None) -> bool:726 """Load "dotenv" files in order of precedence to set environment variables.727728 If an env var is already set it is not overwritten, so earlier files in the729 list are preferred over later files.
4 unmodified lines
734735 :param path: Load the file at this location instead of searching.736 :return: ``True`` if a file was loaded.737594 .. 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.741742 .. versionchanged:: 2.0743 When loading the env files, set the default encoding to UTF-8.744745 .. versionchanged:: 1.1.0746 Returns ``False`` when python-dotenv is not installed, or when747 the given path isn't a file.748749 .. versionadded:: 1.0750 """751 try:752 import dotenv
7 unmodified lines
760 )761762 return False763616 # 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")769770 return False771624 new_dir = None772 loaded = False773774 for name in (".env", ".flaskenv"):775 path = dotenv.find_dotenv(name, usecwd=True)776777 if not path:778 continue779632 if new_dir is None:633 new_dir = os.path.dirname(path)634780 dotenv.load_dotenv(path, encoding="utf-8")781 loaded = True782637 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.784785786def show_server_banner(env, debug, app_import_path, eager_loading):787 """Show extra startup messages the first time the server is run,
194 unmodified lines
982983 This server is for development purposes only. It does not provide984 the stability, security, or performance of production WSGI servers.985840 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()991992 if reload is None:993 reload = debug
1 unmodified line
995 if debugger is None:996 debugger = debug997998 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)852 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)9991000 from werkzeug.serving import run_simple10011002 run_simple(
113 unmodified lines
1116 name="flask",1117 help="""\1118A general utility script for Flask applications.1119974Provides commands from Flask, extensions, and the application. Loads the975application defined in the FLASK_APP environment variable, or from a wsgi.py976file. Setting the FLASK_ENV environment variable to 'development' will enable977debug mode.978979\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 ),1120An application to load must be given with the '--app' option,1121'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file1122in the current directory.1123""",1124)112511261127def main() -> None:
5 unmodified lines
modified:src/flask/helpers.py+3 added-3 removed
46 unmodified lines
47 return val.lower() not in ("0", "false", "no")484950def 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.5455 :param default: What to return if the env var isn't set.56 """57 val = os.environ.get("FLASK_SKIP_DOTENV")
687 unmodified lines
modified:CHANGES.rst+6 added
25 unmodified lines
26 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`363738Version 2.1.339-------------
1291 unmodified lines