cli.py 31 KB

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