Skip to content
Myr

Merge pull request #4606 from pallets/cli-imports

Before adoption: this commit came in with the history the project adopted, so no landing records it.

inline conditional imports for cli behaviors

authored by David Lord · committed by GitHub · parents e322f32, 1232d69 · Browse files · 3 files+40 added−35 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+40 added−35 removed

  • tests:+15 added−4 removed
  • other:+25 added−31 removed

3 files+40 added−35 removed

modified:src/flask/cli.py+22 added-31 removed
7 unmodified lines
8from functools import update_wrapper9from operator import attrgetter10from threading import Lock11from threading import Thread12from typing import Any13from typing import TYPE_CHECKING1213import click14from werkzeug.utils import import_string15
1 unmodified line
17from .helpers import get_debug_flag18from .helpers import get_env19from .helpers import get_load_dotenv2023try:24 import dotenv25except ImportError:26 dotenv = None2128try:29 import ssl30except ImportError:31 ssl = None # type: ignore3233if sys.version_info >= (3, 10):34 from importlib import metadata35else:36 # Use a backport on Python < 3.10.37 #38 # We technically have importlib.metadata on 3.8+,39 # but the API changed in 3.10, so use the backport40 # for consistency.41 if TYPE_CHECKING:42 metadata: Any43 else:44 # we do this to avoid a version dependent mypy error45 # because importlib_metadata is not installed in python3.10+46 import importlib_metadata as metadata474822class NoAppException(click.UsageError):23 """Raised if an application cannot be found or loaded."""2425
466 unmodified lines
492 def _load_plugin_commands(self):493 if self._loaded_plugin_commands:494 return495496 if sys.version_info >= (3, 10):497 from importlib import metadata498 else:499 # Use a backport on Python < 3.10. We technically have500 # importlib.metadata on 3.8+, but the API changed in 3.10,501 # so use the backport for consistency.502 import importlib_metadata as metadata503504 for ep in metadata.entry_points(group="flask.commands"):505 self.add_command(ep.load(), ep.name)506507 self._loaded_plugin_commands = True
87 unmodified lines
595 When loading the env files, set the default encoding to UTF-8.596597 .. versionadded:: 1.0598 """618 if dotenv is None:599 try:600 import dotenv601 except ImportError:602 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):603 click.secho(604 " * Tip: There are .env or .flaskenv files present."605 ' Do "pip install python-dotenv" to use them.',
67 unmodified lines
673 def __init__(self):674 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)675676 def convert(self, value, param, ctx):694 if ssl is None:677 try:678 import ssl679 except ImportError:680 raise click.BadParameter(681 'Using "--cert" requires Python to be compiled with SSL support.',682 ctx,683 param,699 )684 ) from None685686 try:687 return self.path_type(value, param, ctx)688 except click.BadParameter:
24 unmodified lines
713 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.714 """715 cert = ctx.params.get("cert")716 is_adhoc = cert == "adhoc"732 is_context = ssl and isinstance(cert, ssl.SSLContext)717718 try:719 import ssl720 except ImportError:721 is_context = False722 else:723 is_context = isinstance(cert, ssl.SSLContext)724725 if value is not None:726 if is_adhoc:727 raise click.BadParameter(728 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
262 unmodified lines
modified:tests/test_cli.py+15 added-4 removed
16 unmodified lines
17from flask import current_app18from flask import Flask19from flask.cli import AppGroup20from flask.cli import DispatchingApp21from flask.cli import dotenv21from flask.cli import find_best_app22from flask.cli import FlaskGroup23from flask.cli import get_version24from flask.cli import load_dotenv
465 unmodified lines
490 assert result.exit_code == 0491 assert "No routes were registered." in result.output492493495need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")494def dotenv_not_available():495 try:496 import dotenv # noqa: F401497 except ImportError:498 return True499500 return False501502503need_dotenv = pytest.mark.skipif(504 dotenv_not_available(), reason="dotenv is not installed"505)506507508@need_dotenv509def test_load_dotenv(monkeypatch):510 # can't use monkeypatch.delitem since the keys don't exist yet511 for item in ("FOO", "BAR", "SPAM", "HAM"):
27 unmodified lines
539 assert "FOO" in os.environ540541542def test_dotenv_optional(monkeypatch):533 monkeypatch.setattr("flask.cli.dotenv", None)543 monkeypatch.setitem(sys.modules, "dotenv", None)544 monkeypatch.chdir(test_path)545 load_dotenv()546 assert "FOO" not in os.environ547
63 unmodified lines
611 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])612613614def test_run_cert_no_ssl(monkeypatch):605 monkeypatch.setattr("flask.cli.ssl", None)615 monkeypatch.setitem(sys.modules, "ssl", None)616617 with pytest.raises(click.BadParameter):618 run_command.make_context("run", ["--cert", "not_here"])619620
50 unmodified lines
modified:setup.cfg+3 added
114 unmodified lines
115ignore_missing_imports = True116117[mypy-cryptography.*]118ignore_missing_imports = True119120[mypy-importlib_metadata]121ignore_missing_imports = True