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
Provenance
- Commit
31aad11- Tree
c2bbaca- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e322f32- Parent 2
1232d69
3 files changed+40 added−35 removed
modified:src/flask/cli.py+22 added-31 removed
7 unmodified lines8 from functools import update_wrapper9 from operator import attrgetter10 from threading import Lock11 from threading import Thread12-from typing import Any13-from typing import TYPE_CHECKING12 13 import click14 from werkzeug.utils import import_string15 1 unmodified line17 from .helpers import get_debug_flag18 from .helpers import get_env19 from .helpers import get_load_dotenv20 23-try:24- import dotenv25-except ImportError:26- dotenv = None21 28-try:29- import ssl30-except ImportError:31- ssl = None # type: ignore32-33-if sys.version_info >= (3, 10):34- from importlib import metadata35-else: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 metadata47-48-22 class NoAppException(click.UsageError):23 """Raised if an application cannot be found or loaded."""24 25 466 unmodified lines492 def _load_plugin_commands(self):493 if self._loaded_plugin_commands:494 return495 496+ 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 metadata503+504 for ep in metadata.entry_points(group="flask.commands"):505 self.add_command(ep.load(), ep.name)506 507 self._loaded_plugin_commands = True87 unmodified lines595 When loading the env files, set the default encoding to UTF-8.596 597 .. 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 lines673 def __init__(self):674 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)675 676 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 None685 686 try:687 return self.path_type(value, param, ctx)688 except click.BadParameter:24 unmodified lines713 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)717 718+ try:719+ import ssl720+ except ImportError:721+ is_context = False722+ else:723+ is_context = isinstance(cert, ssl.SSLContext)724+725 if value is not None:726 if is_adhoc:727 raise click.BadParameter(728 'When "--cert" is "adhoc", "--key" is not used.', ctx, param262 unmodified linesmodified:tests/test_cli.py+15 added-4 removed
16 unmodified lines17 from flask import current_app18 from flask import Flask19 from flask.cli import AppGroup20 from flask.cli import DispatchingApp21-from flask.cli import dotenv21 from flask.cli import find_best_app22 from flask.cli import FlaskGroup23 from flask.cli import get_version24 from flask.cli import load_dotenv465 unmodified lines490 assert result.exit_code == 0491 assert "No routes were registered." in result.output492 493 495-need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")494+def dotenv_not_available():495+ try:496+ import dotenv # noqa: F401497+ except ImportError:498+ return True499 500+ return False501 502+503+need_dotenv = pytest.mark.skipif(504+ dotenv_not_available(), reason="dotenv is not installed"505+)506+507+508 @need_dotenv509 def 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 lines539 assert "FOO" in os.environ540 541 542 def 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 lines611 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])612 613 614 def test_run_cert_no_ssl(monkeypatch):605- monkeypatch.setattr("flask.cli.ssl", None)615+ monkeypatch.setitem(sys.modules, "ssl", None)616+617 with pytest.raises(click.BadParameter):618 run_command.make_context("run", ["--cert", "not_here"])619 620 50 unmodified linesmodified:setup.cfg+3 added
114 unmodified lines115 ignore_missing_imports = True116 117 [mypy-cryptography.*]118 ignore_missing_imports = True119+120+[mypy-importlib_metadata]121+ignore_missing_imports = True