cli.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. from __future__ import annotations
  2. import ast
  3. import inspect
  4. import os
  5. import platform
  6. import re
  7. import sys
  8. import traceback
  9. import typing as t
  10. from functools import update_wrapper
  11. from operator import attrgetter
  12. import click
  13. from click.core import ParameterSource
  14. from werkzeug import run_simple
  15. from werkzeug.serving import is_running_from_reloader
  16. from werkzeug.utils import import_string
  17. from .globals import current_app
  18. from .helpers import get_debug_flag
  19. from .helpers import get_load_dotenv
  20. if t.TYPE_CHECKING:
  21. from .app import Flask
  22. class NoAppException(click.UsageError):
  23. """Raised if an application cannot be found or loaded."""
  24. def find_best_app(module):
  25. """Given a module instance this tries to find the best possible
  26. application in the module or raises an exception.
  27. """
  28. from . import Flask
  29. # Search for the most common names first.
  30. for attr_name in ("app", "application"):
  31. app = getattr(module, attr_name, None)
  32. if isinstance(app, Flask):
  33. return app
  34. # Otherwise find the only object that is a Flask instance.
  35. matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]
  36. if len(matches) == 1:
  37. return matches[0]
  38. elif len(matches) > 1:
  39. raise NoAppException(
  40. "Detected multiple Flask applications in module"
  41. f" '{module.__name__}'. Use '{module.__name__}:name'"
  42. " to specify the correct one."
  43. )
  44. # Search for app factory functions.
  45. for attr_name in ("create_app", "make_app"):
  46. app_factory = getattr(module, attr_name, None)
  47. if inspect.isfunction(app_factory):
  48. try:
  49. app = app_factory()
  50. if isinstance(app, Flask):
  51. return app
  52. except TypeError as e:
  53. if not _called_with_wrong_args(app_factory):
  54. raise
  55. raise NoAppException(
  56. f"Detected factory '{attr_name}' in module '{module.__name__}',"
  57. " but could not call it without arguments. Use"
  58. f" '{module.__name__}:{attr_name}(args)'"
  59. " to specify arguments."
  60. ) from e
  61. raise NoAppException(
  62. "Failed to find Flask application or factory in module"
  63. f" '{module.__name__}'. Use '{module.__name__}:name'"
  64. " to specify one."
  65. )
  66. def _called_with_wrong_args(f):
  67. """Check whether calling a function raised a ``TypeError`` because
  68. the call failed or because something in the factory raised the
  69. error.
  70. :param f: The function that was called.
  71. :return: ``True`` if the call failed.
  72. """
  73. tb = sys.exc_info()[2]
  74. try:
  75. while tb is not None:
  76. if tb.tb_frame.f_code is f.__code__:
  77. # In the function, it was called successfully.
  78. return False
  79. tb = tb.tb_next
  80. # Didn't reach the function.
  81. return True
  82. finally:
  83. # Delete tb to break a circular reference.
  84. # https://docs.python.org/2/library/sys.html#sys.exc_info
  85. del tb
  86. def find_app_by_string(module, app_name):
  87. """Check if the given string is a variable name or a function. Call
  88. a function to get the app instance, or return the variable directly.
  89. """
  90. from . import Flask
  91. # Parse app_name as a single expression to determine if it's a valid
  92. # attribute name or function call.
  93. try:
  94. expr = ast.parse(app_name.strip(), mode="eval").body
  95. except SyntaxError:
  96. raise NoAppException(
  97. f"Failed to parse {app_name!r} as an attribute name or function call."
  98. ) from None
  99. if isinstance(expr, ast.Name):
  100. name = expr.id
  101. args = []
  102. kwargs = {}
  103. elif isinstance(expr, ast.Call):
  104. # Ensure the function name is an attribute name only.
  105. if not isinstance(expr.func, ast.Name):
  106. raise NoAppException(
  107. f"Function reference must be a simple name: {app_name!r}."
  108. )
  109. name = expr.func.id
  110. # Parse the positional and keyword arguments as literals.
  111. try:
  112. args = [ast.literal_eval(arg) for arg in expr.args]
  113. kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}
  114. except ValueError:
  115. # literal_eval gives cryptic error messages, show a generic
  116. # message with the full expression instead.
  117. raise NoAppException(
  118. f"Failed to parse arguments as literal values: {app_name!r}."
  119. ) from None
  120. else:
  121. raise NoAppException(
  122. f"Failed to parse {app_name!r} as an attribute name or function call."
  123. )
  124. try:
  125. attr = getattr(module, name)
  126. except AttributeError as e:
  127. raise NoAppException(
  128. f"Failed to find attribute {name!r} in {module.__name__!r}."
  129. ) from e
  130. # If the attribute is a function, call it with any args and kwargs
  131. # to get the real application.
  132. if inspect.isfunction(attr):
  133. try:
  134. app = attr(*args, **kwargs)
  135. except TypeError as e:
  136. if not _called_with_wrong_args(attr):
  137. raise
  138. raise NoAppException(
  139. f"The factory {app_name!r} in module"
  140. f" {module.__name__!r} could not be called with the"
  141. " specified arguments."
  142. ) from e
  143. else:
  144. app = attr
  145. if isinstance(app, Flask):
  146. return app
  147. raise NoAppException(
  148. "A valid Flask application was not obtained from"
  149. f" '{module.__name__}:{app_name}'."
  150. )
  151. def prepare_import(path):
  152. """Given a filename this will try to calculate the python path, add it
  153. to the search path and return the actual module name that is expected.
  154. """
  155. path = os.path.realpath(path)
  156. fname, ext = os.path.splitext(path)
  157. if ext == ".py":
  158. path = fname
  159. if os.path.basename(path) == "__init__":
  160. path = os.path.dirname(path)
  161. module_name = []
  162. # move up until outside package structure (no __init__.py)
  163. while True:
  164. path, name = os.path.split(path)
  165. module_name.append(name)
  166. if not os.path.exists(os.path.join(path, "__init__.py")):
  167. break
  168. if sys.path[0] != path:
  169. sys.path.insert(0, path)
  170. return ".".join(module_name[::-1])
  171. def locate_app(module_name, app_name, raise_if_not_found=True):
  172. try:
  173. __import__(module_name)
  174. except ImportError:
  175. # Reraise the ImportError if it occurred within the imported module.
  176. # Determine this by checking whether the trace has a depth > 1.
  177. if sys.exc_info()[2].tb_next:
  178. raise NoAppException(
  179. f"While importing {module_name!r}, an ImportError was"
  180. f" raised:\n\n{traceback.format_exc()}"
  181. ) from None
  182. elif raise_if_not_found:
  183. raise NoAppException(f"Could not import {module_name!r}.") from None
  184. else:
  185. return
  186. module = sys.modules[module_name]
  187. if app_name is None:
  188. return find_best_app(module)
  189. else:
  190. return find_app_by_string(module, app_name)
  191. def get_version(ctx, param, value):
  192. if not value or ctx.resilient_parsing:
  193. return
  194. import werkzeug
  195. from . import __version__
  196. click.echo(
  197. f"Python {platform.python_version()}\n"
  198. f"Flask {__version__}\n"
  199. f"Werkzeug {werkzeug.__version__}",
  200. color=ctx.color,
  201. )
  202. ctx.exit()
  203. version_option = click.Option(
  204. ["--version"],
  205. help="Show the Flask version.",
  206. expose_value=False,
  207. callback=get_version,
  208. is_flag=True,
  209. is_eager=True,
  210. )
  211. class ScriptInfo:
  212. """Helper object to deal with Flask applications. This is usually not
  213. necessary to interface with as it's used internally in the dispatching
  214. to click. In future versions of Flask this object will most likely play
  215. a bigger role. Typically it's created automatically by the
  216. :class:`FlaskGroup` but you can also manually create it and pass it
  217. onwards as click object.
  218. """
  219. def __init__(
  220. self,
  221. app_import_path: str | None = None,
  222. create_app: t.Callable[..., Flask] | None = None,
  223. set_debug_flag: bool = True,
  224. ) -> None:
  225. #: Optionally the import path for the Flask application.
  226. self.app_import_path = app_import_path
  227. #: Optionally a function that is passed the script info to create
  228. #: the instance of the application.
  229. self.create_app = create_app
  230. #: A dictionary with arbitrary data that can be associated with
  231. #: this script info.
  232. self.data: t.Dict[t.Any, t.Any] = {}
  233. self.set_debug_flag = set_debug_flag
  234. self._loaded_app: Flask | None = None
  235. def load_app(self) -> Flask:
  236. """Loads the Flask app (if not yet loaded) and returns it. Calling
  237. this multiple times will just result in the already loaded app to
  238. be returned.
  239. """
  240. if self._loaded_app is not None:
  241. return self._loaded_app
  242. if self.create_app is not None:
  243. app = self.create_app()
  244. else:
  245. if self.app_import_path:
  246. path, name = (
  247. re.split(r":(?![\\/])", self.app_import_path, 1) + [None]
  248. )[:2]
  249. import_name = prepare_import(path)
  250. app = locate_app(import_name, name)
  251. else:
  252. for path in ("wsgi.py", "app.py"):
  253. import_name = prepare_import(path)
  254. app = locate_app(import_name, None, raise_if_not_found=False)
  255. if app:
  256. break
  257. if not app:
  258. raise NoAppException(
  259. "Could not locate a Flask application. Use the"
  260. " 'flask --app' option, 'FLASK_APP' environment"
  261. " variable, or a 'wsgi.py' or 'app.py' file in the"
  262. " current directory."
  263. )
  264. if self.set_debug_flag:
  265. # Update the app's debug flag through the descriptor so that
  266. # other values repopulate as well.
  267. app.debug = get_debug_flag()
  268. self._loaded_app = app
  269. return app
  270. pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
  271. def with_appcontext(f):
  272. """Wraps a callback so that it's guaranteed to be executed with the
  273. script's application context.
  274. Custom commands (and their options) registered under ``app.cli`` or
  275. ``blueprint.cli`` will always have an app context available, this
  276. decorator is not required in that case.
  277. .. versionchanged:: 2.2
  278. The app context is active for subcommands as well as the
  279. decorated callback. The app context is always available to
  280. ``app.cli`` command and parameter callbacks.
  281. """
  282. @click.pass_context
  283. def decorator(__ctx, *args, **kwargs):
  284. if not current_app:
  285. app = __ctx.ensure_object(ScriptInfo).load_app()
  286. __ctx.with_resource(app.app_context())
  287. return __ctx.invoke(f, *args, **kwargs)
  288. return update_wrapper(decorator, f)
  289. class AppGroup(click.Group):
  290. """This works similar to a regular click :class:`~click.Group` but it
  291. changes the behavior of the :meth:`command` decorator so that it
  292. automatically wraps the functions in :func:`with_appcontext`.
  293. Not to be confused with :class:`FlaskGroup`.
  294. """
  295. def command(self, *args, **kwargs):
  296. """This works exactly like the method of the same name on a regular
  297. :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
  298. unless it's disabled by passing ``with_appcontext=False``.
  299. """
  300. wrap_for_ctx = kwargs.pop("with_appcontext", True)
  301. def decorator(f):
  302. if wrap_for_ctx:
  303. f = with_appcontext(f)
  304. return click.Group.command(self, *args, **kwargs)(f)
  305. return decorator
  306. def group(self, *args, **kwargs):
  307. """This works exactly like the method of the same name on a regular
  308. :class:`click.Group` but it defaults the group class to
  309. :class:`AppGroup`.
  310. """
  311. kwargs.setdefault("cls", AppGroup)
  312. return click.Group.group(self, *args, **kwargs)
  313. def _set_app(ctx: click.Context, param: click.Option, value: str | None) -> str | None:
  314. if value is None:
  315. return None
  316. info = ctx.ensure_object(ScriptInfo)
  317. info.app_import_path = value
  318. return value
  319. # This option is eager so the app will be available if --help is given.
  320. # --help is also eager, so --app must be before it in the param list.
  321. # no_args_is_help bypasses eager processing, so this option must be
  322. # processed manually in that case to ensure FLASK_APP gets picked up.
  323. _app_option = click.Option(
  324. ["-A", "--app"],
  325. metavar="IMPORT",
  326. help=(
  327. "The Flask application or factory function to load, in the form 'module:name'."
  328. " Module can be a dotted import or file path. Name is not required if it is"
  329. " 'app', 'application', 'create_app', or 'make_app', and can be 'name(args)' to"
  330. " pass arguments."
  331. ),
  332. is_eager=True,
  333. expose_value=False,
  334. callback=_set_app,
  335. )
  336. def _set_debug(ctx: click.Context, param: click.Option, value: bool) -> bool | None:
  337. # If the flag isn't provided, it will default to False. Don't use
  338. # that, let debug be set by env in that case.
  339. source = ctx.get_parameter_source(param.name) # type: ignore[arg-type]
  340. if source is not None and source in (
  341. ParameterSource.DEFAULT,
  342. ParameterSource.DEFAULT_MAP,
  343. ):
  344. return None
  345. # Set with env var instead of ScriptInfo.load so that it can be
  346. # accessed early during a factory function.
  347. os.environ["FLASK_DEBUG"] = "1" if value else "0"
  348. return value
  349. _debug_option = click.Option(
  350. ["--debug/--no-debug"],
  351. help="Set debug mode.",
  352. expose_value=False,
  353. callback=_set_debug,
  354. )
  355. def _env_file_callback(
  356. ctx: click.Context, param: click.Option, value: str | None
  357. ) -> str | None:
  358. if value is None:
  359. return None
  360. import importlib
  361. try:
  362. importlib.import_module("dotenv")
  363. except ImportError:
  364. raise click.BadParameter(
  365. "python-dotenv must be installed to load an env file.",
  366. ctx=ctx,
  367. param=param,
  368. ) from None
  369. # Don't check FLASK_SKIP_DOTENV, that only disables automatically
  370. # loading .env and .flaskenv files.
  371. load_dotenv(value)
  372. return value
  373. # This option is eager so env vars are loaded as early as possible to be
  374. # used by other options.
  375. _env_file_option = click.Option(
  376. ["-e", "--env-file"],
  377. type=click.Path(exists=True, dir_okay=False),
  378. help="Load environment variables from this file. python-dotenv must be installed.",
  379. is_eager=True,
  380. expose_value=False,
  381. callback=_env_file_callback,
  382. )
  383. class FlaskGroup(AppGroup):
  384. """Special subclass of the :class:`AppGroup` group that supports
  385. loading more commands from the configured Flask app. Normally a
  386. developer does not have to interface with this class but there are
  387. some very advanced use cases for which it makes sense to create an
  388. instance of this. see :ref:`custom-scripts`.
  389. :param add_default_commands: if this is True then the default run and
  390. shell commands will be added.
  391. :param add_version_option: adds the ``--version`` option.
  392. :param create_app: an optional callback that is passed the script info and
  393. returns the loaded app.
  394. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  395. files to set environment variables. Will also change the working
  396. directory to the directory containing the first file found.
  397. :param set_debug_flag: Set the app's debug flag.
  398. .. versionchanged:: 2.2
  399. Added the ``-A/--app``, ``--debug/--no-debug``, ``-e/--env-file`` options.
  400. .. versionchanged:: 2.2
  401. An app context is pushed when running ``app.cli`` commands, so
  402. ``@with_appcontext`` is no longer required for those commands.
  403. .. versionchanged:: 1.0
  404. If installed, python-dotenv will be used to load environment variables
  405. from :file:`.env` and :file:`.flaskenv` files.
  406. """
  407. def __init__(
  408. self,
  409. add_default_commands: bool = True,
  410. create_app: t.Callable[..., Flask] | None = None,
  411. add_version_option: bool = True,
  412. load_dotenv: bool = True,
  413. set_debug_flag: bool = True,
  414. **extra: t.Any,
  415. ) -> None:
  416. params = list(extra.pop("params", None) or ())
  417. # Processing is done with option callbacks instead of a group
  418. # callback. This allows users to make a custom group callback
  419. # without losing the behavior. --env-file must come first so
  420. # that it is eagerly evaluated before --app.
  421. params.extend((_env_file_option, _app_option, _debug_option))
  422. if add_version_option:
  423. params.append(version_option)
  424. if "context_settings" not in extra:
  425. extra["context_settings"] = {}
  426. extra["context_settings"].setdefault("auto_envvar_prefix", "FLASK")
  427. super().__init__(params=params, **extra)
  428. self.create_app = create_app
  429. self.load_dotenv = load_dotenv
  430. self.set_debug_flag = set_debug_flag
  431. if add_default_commands:
  432. self.add_command(run_command)
  433. self.add_command(shell_command)
  434. self.add_command(routes_command)
  435. self._loaded_plugin_commands = False
  436. def _load_plugin_commands(self):
  437. if self._loaded_plugin_commands:
  438. return
  439. if sys.version_info >= (3, 10):
  440. from importlib import metadata
  441. else:
  442. # Use a backport on Python < 3.10. We technically have
  443. # importlib.metadata on 3.8+, but the API changed in 3.10,
  444. # so use the backport for consistency.
  445. import importlib_metadata as metadata
  446. for ep in metadata.entry_points(group="flask.commands"):
  447. self.add_command(ep.load(), ep.name)
  448. self._loaded_plugin_commands = True
  449. def get_command(self, ctx, name):
  450. self._load_plugin_commands()
  451. # Look up built-in and plugin commands, which should be
  452. # available even if the app fails to load.
  453. rv = super().get_command(ctx, name)
  454. if rv is not None:
  455. return rv
  456. info = ctx.ensure_object(ScriptInfo)
  457. # Look up commands provided by the app, showing an error and
  458. # continuing if the app couldn't be loaded.
  459. try:
  460. app = info.load_app()
  461. except NoAppException as e:
  462. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  463. return None
  464. # Push an app context for the loaded app unless it is already
  465. # active somehow. This makes the context available to parameter
  466. # and command callbacks without needing @with_appcontext.
  467. if not current_app or current_app._get_current_object() is not app:
  468. ctx.with_resource(app.app_context())
  469. return app.cli.get_command(ctx, name)
  470. def list_commands(self, ctx):
  471. self._load_plugin_commands()
  472. # Start with the built-in and plugin commands.
  473. rv = set(super().list_commands(ctx))
  474. info = ctx.ensure_object(ScriptInfo)
  475. # Add commands provided by the app, showing an error and
  476. # continuing if the app couldn't be loaded.
  477. try:
  478. rv.update(info.load_app().cli.list_commands(ctx))
  479. except NoAppException as e:
  480. # When an app couldn't be loaded, show the error message
  481. # without the traceback.
  482. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  483. except Exception:
  484. # When any other errors occurred during loading, show the
  485. # full traceback.
  486. click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")
  487. return sorted(rv)
  488. def make_context(
  489. self,
  490. info_name: str | None,
  491. args: list[str],
  492. parent: click.Context | None = None,
  493. **extra: t.Any,
  494. ) -> click.Context:
  495. # Set a flag to tell app.run to become a no-op. If app.run was
  496. # not in a __name__ == __main__ guard, it would start the server
  497. # when importing, blocking whatever command is being called.
  498. os.environ["FLASK_RUN_FROM_CLI"] = "true"
  499. # Attempt to load .env and .flask env files. The --env-file
  500. # option can cause another file to be loaded.
  501. if get_load_dotenv(self.load_dotenv):
  502. load_dotenv()
  503. if "obj" not in extra and "obj" not in self.context_settings:
  504. extra["obj"] = ScriptInfo(
  505. create_app=self.create_app, set_debug_flag=self.set_debug_flag
  506. )
  507. return super().make_context(info_name, args, parent=parent, **extra)
  508. def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
  509. if not args and self.no_args_is_help:
  510. # Attempt to load --env-file and --app early in case they
  511. # were given as env vars. Otherwise no_args_is_help will not
  512. # see commands from app.cli.
  513. _env_file_option.handle_parse_result(ctx, {}, [])
  514. _app_option.handle_parse_result(ctx, {}, [])
  515. return super().parse_args(ctx, args)
  516. def _path_is_ancestor(path, other):
  517. """Take ``other`` and remove the length of ``path`` from it. Then join it
  518. to ``path``. If it is the original value, ``path`` is an ancestor of
  519. ``other``."""
  520. return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
  521. def load_dotenv(path: str | os.PathLike | None = None) -> bool:
  522. """Load "dotenv" files in order of precedence to set environment variables.
  523. If an env var is already set it is not overwritten, so earlier files in the
  524. list are preferred over later files.
  525. This is a no-op if `python-dotenv`_ is not installed.
  526. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
  527. :param path: Load the file at this location instead of searching.
  528. :return: ``True`` if a file was loaded.
  529. .. versionchanged:: 2.0
  530. The current directory is not changed to the location of the
  531. loaded file.
  532. .. versionchanged:: 2.0
  533. When loading the env files, set the default encoding to UTF-8.
  534. .. versionchanged:: 1.1.0
  535. Returns ``False`` when python-dotenv is not installed, or when
  536. the given path isn't a file.
  537. .. versionadded:: 1.0
  538. """
  539. try:
  540. import dotenv
  541. except ImportError:
  542. if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
  543. click.secho(
  544. " * Tip: There are .env or .flaskenv files present."
  545. ' Do "pip install python-dotenv" to use them.',
  546. fg="yellow",
  547. err=True,
  548. )
  549. return False
  550. # Always return after attempting to load a given path, don't load
  551. # the default files.
  552. if path is not None:
  553. if os.path.isfile(path):
  554. return dotenv.load_dotenv(path, encoding="utf-8")
  555. return False
  556. loaded = False
  557. for name in (".env", ".flaskenv"):
  558. path = dotenv.find_dotenv(name, usecwd=True)
  559. if not path:
  560. continue
  561. dotenv.load_dotenv(path, encoding="utf-8")
  562. loaded = True
  563. return loaded # True if at least one file was located and loaded.
  564. def show_server_banner(debug, app_import_path):
  565. """Show extra startup messages the first time the server is run,
  566. ignoring the reloader.
  567. """
  568. if is_running_from_reloader():
  569. return
  570. if app_import_path is not None:
  571. click.echo(f" * Serving Flask app '{app_import_path}'")
  572. if debug is not None:
  573. click.echo(f" * Debug mode: {'on' if debug else 'off'}")
  574. class CertParamType(click.ParamType):
  575. """Click option type for the ``--cert`` option. Allows either an
  576. existing file, the string ``'adhoc'``, or an import for a
  577. :class:`~ssl.SSLContext` object.
  578. """
  579. name = "path"
  580. def __init__(self):
  581. self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)
  582. def convert(self, value, param, ctx):
  583. try:
  584. import ssl
  585. except ImportError:
  586. raise click.BadParameter(
  587. 'Using "--cert" requires Python to be compiled with SSL support.',
  588. ctx,
  589. param,
  590. ) from None
  591. try:
  592. return self.path_type(value, param, ctx)
  593. except click.BadParameter:
  594. value = click.STRING(value, param, ctx).lower()
  595. if value == "adhoc":
  596. try:
  597. import cryptography # noqa: F401
  598. except ImportError:
  599. raise click.BadParameter(
  600. "Using ad-hoc certificates requires the cryptography library.",
  601. ctx,
  602. param,
  603. ) from None
  604. return value
  605. obj = import_string(value, silent=True)
  606. if isinstance(obj, ssl.SSLContext):
  607. return obj
  608. raise
  609. def _validate_key(ctx, param, value):
  610. """The ``--key`` option must be specified when ``--cert`` is a file.
  611. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
  612. """
  613. cert = ctx.params.get("cert")
  614. is_adhoc = cert == "adhoc"
  615. try:
  616. import ssl
  617. except ImportError:
  618. is_context = False
  619. else:
  620. is_context = isinstance(cert, ssl.SSLContext)
  621. if value is not None:
  622. if is_adhoc:
  623. raise click.BadParameter(
  624. 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
  625. )
  626. if is_context:
  627. raise click.BadParameter(
  628. 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param
  629. )
  630. if not cert:
  631. raise click.BadParameter('"--cert" must also be specified.', ctx, param)
  632. ctx.params["cert"] = cert, value
  633. else:
  634. if cert and not (is_adhoc or is_context):
  635. raise click.BadParameter('Required when using "--cert".', ctx, param)
  636. return value
  637. class SeparatedPathType(click.Path):
  638. """Click option type that accepts a list of values separated by the
  639. OS's path separator (``:``, ``;`` on Windows). Each value is
  640. validated as a :class:`click.Path` type.
  641. """
  642. def convert(self, value, param, ctx):
  643. items = self.split_envvar_value(value)
  644. super_convert = super().convert
  645. return [super_convert(item, param, ctx) for item in items]
  646. @click.command("run", short_help="Run a development server.")
  647. @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
  648. @click.option("--port", "-p", default=5000, help="The port to bind to.")
  649. @click.option(
  650. "--cert",
  651. type=CertParamType(),
  652. help="Specify a certificate file to use HTTPS.",
  653. is_eager=True,
  654. )
  655. @click.option(
  656. "--key",
  657. type=click.Path(exists=True, dir_okay=False, resolve_path=True),
  658. callback=_validate_key,
  659. expose_value=False,
  660. help="The key file to use when specifying a certificate.",
  661. )
  662. @click.option(
  663. "--reload/--no-reload",
  664. default=None,
  665. help="Enable or disable the reloader. By default the reloader "
  666. "is active if debug is enabled.",
  667. )
  668. @click.option(
  669. "--debugger/--no-debugger",
  670. default=None,
  671. help="Enable or disable the debugger. By default the debugger "
  672. "is active if debug is enabled.",
  673. )
  674. @click.option(
  675. "--with-threads/--without-threads",
  676. default=True,
  677. help="Enable or disable multithreading.",
  678. )
  679. @click.option(
  680. "--extra-files",
  681. default=None,
  682. type=SeparatedPathType(),
  683. help=(
  684. "Extra files that trigger a reload on change. Multiple paths"
  685. f" are separated by {os.path.pathsep!r}."
  686. ),
  687. )
  688. @click.option(
  689. "--exclude-patterns",
  690. default=None,
  691. type=SeparatedPathType(),
  692. help=(
  693. "Files matching these fnmatch patterns will not trigger a reload"
  694. " on change. Multiple patterns are separated by"
  695. f" {os.path.pathsep!r}."
  696. ),
  697. )
  698. @pass_script_info
  699. def run_command(
  700. info,
  701. host,
  702. port,
  703. reload,
  704. debugger,
  705. with_threads,
  706. cert,
  707. extra_files,
  708. exclude_patterns,
  709. ):
  710. """Run a local development server.
  711. This server is for development purposes only. It does not provide
  712. the stability, security, or performance of production WSGI servers.
  713. The reloader and debugger are enabled by default with the '--debug'
  714. option.
  715. """
  716. try:
  717. app = info.load_app()
  718. except Exception as e:
  719. if is_running_from_reloader():
  720. # When reloading, print out the error immediately, but raise
  721. # it later so the debugger or server can handle it.
  722. traceback.print_exc()
  723. err = e
  724. def app(environ, start_response):
  725. raise err from None
  726. else:
  727. # When not reloading, raise the error immediately so the
  728. # command fails.
  729. raise e from None
  730. debug = get_debug_flag()
  731. if reload is None:
  732. reload = debug
  733. if debugger is None:
  734. debugger = debug
  735. show_server_banner(debug, info.app_import_path)
  736. run_simple(
  737. host,
  738. port,
  739. app,
  740. use_reloader=reload,
  741. use_debugger=debugger,
  742. threaded=with_threads,
  743. ssl_context=cert,
  744. extra_files=extra_files,
  745. exclude_patterns=exclude_patterns,
  746. )
  747. @click.command("shell", short_help="Run a shell in the app context.")
  748. @with_appcontext
  749. def shell_command() -> None:
  750. """Run an interactive Python shell in the context of a given
  751. Flask application. The application will populate the default
  752. namespace of this shell according to its configuration.
  753. This is useful for executing small snippets of management code
  754. without having to manually configure the application.
  755. """
  756. import code
  757. banner = (
  758. f"Python {sys.version} on {sys.platform}\n"
  759. f"App: {current_app.import_name}\n"
  760. f"Instance: {current_app.instance_path}"
  761. )
  762. ctx: dict = {}
  763. # Support the regular Python interpreter startup script if someone
  764. # is using it.
  765. startup = os.environ.get("PYTHONSTARTUP")
  766. if startup and os.path.isfile(startup):
  767. with open(startup) as f:
  768. eval(compile(f.read(), startup, "exec"), ctx)
  769. ctx.update(current_app.make_shell_context())
  770. # Site, customize, or startup script can set a hook to call when
  771. # entering interactive mode. The default one sets up readline with
  772. # tab and history completion.
  773. interactive_hook = getattr(sys, "__interactivehook__", None)
  774. if interactive_hook is not None:
  775. try:
  776. import readline
  777. from rlcompleter import Completer
  778. except ImportError:
  779. pass
  780. else:
  781. # rlcompleter uses __main__.__dict__ by default, which is
  782. # flask.__main__. Use the shell context instead.
  783. readline.set_completer(Completer(ctx).complete)
  784. interactive_hook()
  785. code.interact(banner=banner, local=ctx)
  786. @click.command("routes", short_help="Show the routes for the app.")
  787. @click.option(
  788. "--sort",
  789. "-s",
  790. type=click.Choice(("endpoint", "methods", "rule", "match")),
  791. default="endpoint",
  792. help=(
  793. 'Method to sort routes by. "match" is the order that Flask will match '
  794. "routes when dispatching a request."
  795. ),
  796. )
  797. @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
  798. @with_appcontext
  799. def routes_command(sort: str, all_methods: bool) -> None:
  800. """Show all registered routes with endpoints and methods."""
  801. rules = list(current_app.url_map.iter_rules())
  802. if not rules:
  803. click.echo("No routes were registered.")
  804. return
  805. ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))
  806. if sort in ("endpoint", "rule"):
  807. rules = sorted(rules, key=attrgetter(sort))
  808. elif sort == "methods":
  809. rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore
  810. rule_methods = [
  811. ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore
  812. for rule in rules
  813. ]
  814. headers = ("Endpoint", "Methods", "Rule")
  815. widths = (
  816. max(len(rule.endpoint) for rule in rules),
  817. max(len(methods) for methods in rule_methods),
  818. max(len(rule.rule) for rule in rules),
  819. )
  820. widths = [max(len(h), w) for h, w in zip(headers, widths)]
  821. row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)
  822. click.echo(row.format(*headers).strip())
  823. click.echo(row.format(*("-" * width for width in widths)))
  824. for rule, methods in zip(rules, rule_methods):
  825. click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())
  826. cli = FlaskGroup(
  827. name="flask",
  828. help="""\
  829. A general utility script for Flask applications.
  830. An application to load must be given with the '--app' option,
  831. 'FLASK_APP' environment variable, or with a 'wsgi.py' or 'app.py' file
  832. in the current directory.
  833. """,
  834. )
  835. def main() -> None:
  836. cli.main()
  837. if __name__ == "__main__":
  838. main()