cli.py 31 KB

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