cli.py 33 KB

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