cli.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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:
  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"
  215. f" raised:\n\n{traceback.format_exc()}"
  216. ) from None
  217. elif raise_if_not_found:
  218. raise NoAppException(f"Could not import {module_name!r}.") from None
  219. else:
  220. return
  221. module = sys.modules[module_name]
  222. if app_name is None:
  223. return find_best_app(script_info, module)
  224. else:
  225. return find_app_by_string(script_info, module, app_name)
  226. def get_version(ctx, param, value):
  227. if not value or ctx.resilient_parsing:
  228. return
  229. import werkzeug
  230. from . import __version__
  231. click.echo(
  232. f"Python {platform.python_version()}\n"
  233. f"Flask {__version__}\n"
  234. f"Werkzeug {werkzeug.__version__}",
  235. color=ctx.color,
  236. )
  237. ctx.exit()
  238. version_option = click.Option(
  239. ["--version"],
  240. help="Show the flask version",
  241. expose_value=False,
  242. callback=get_version,
  243. is_flag=True,
  244. is_eager=True,
  245. )
  246. class DispatchingApp:
  247. """Special application that dispatches to a Flask application which
  248. is imported by name in a background thread. If an error happens
  249. it is recorded and shown as part of the WSGI handling which in case
  250. of the Werkzeug debugger means that it shows up in the browser.
  251. """
  252. def __init__(self, loader, use_eager_loading=None):
  253. self.loader = loader
  254. self._app = None
  255. self._lock = Lock()
  256. self._bg_loading_exc = None
  257. if use_eager_loading is None:
  258. use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"
  259. if use_eager_loading:
  260. self._load_unlocked()
  261. else:
  262. self._load_in_background()
  263. def _load_in_background(self):
  264. def _load_app():
  265. __traceback_hide__ = True # noqa: F841
  266. with self._lock:
  267. try:
  268. self._load_unlocked()
  269. except Exception as e:
  270. self._bg_loading_exc = e
  271. t = Thread(target=_load_app, args=())
  272. t.start()
  273. def _flush_bg_loading_exception(self):
  274. __traceback_hide__ = True # noqa: F841
  275. exc = self._bg_loading_exc
  276. if exc is not None:
  277. self._bg_loading_exc = None
  278. raise exc
  279. def _load_unlocked(self):
  280. __traceback_hide__ = True # noqa: F841
  281. self._app = rv = self.loader()
  282. self._bg_loading_exc = None
  283. return rv
  284. def __call__(self, environ, start_response):
  285. __traceback_hide__ = True # noqa: F841
  286. if self._app is not None:
  287. return self._app(environ, start_response)
  288. self._flush_bg_loading_exception()
  289. with self._lock:
  290. if self._app is not None:
  291. rv = self._app
  292. else:
  293. rv = self._load_unlocked()
  294. return rv(environ, start_response)
  295. class ScriptInfo:
  296. """Helper object to deal with Flask applications. This is usually not
  297. necessary to interface with as it's used internally in the dispatching
  298. to click. In future versions of Flask this object will most likely play
  299. a bigger role. Typically it's created automatically by the
  300. :class:`FlaskGroup` but you can also manually create it and pass it
  301. onwards as click object.
  302. """
  303. def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):
  304. #: Optionally the import path for the Flask application.
  305. self.app_import_path = app_import_path or os.environ.get("FLASK_APP")
  306. #: Optionally a function that is passed the script info to create
  307. #: the instance of the application.
  308. self.create_app = create_app
  309. #: A dictionary with arbitrary data that can be associated with
  310. #: this script info.
  311. self.data = {}
  312. self.set_debug_flag = set_debug_flag
  313. self._loaded_app = None
  314. def load_app(self):
  315. """Loads the Flask app (if not yet loaded) and returns it. Calling
  316. this multiple times will just result in the already loaded app to
  317. be returned.
  318. """
  319. __traceback_hide__ = True # noqa: F841
  320. if self._loaded_app is not None:
  321. return self._loaded_app
  322. if self.create_app is not None:
  323. app = call_factory(self, self.create_app)
  324. else:
  325. if self.app_import_path:
  326. path, name = (
  327. re.split(r":(?![\\/])", self.app_import_path, 1) + [None]
  328. )[:2]
  329. import_name = prepare_import(path)
  330. app = locate_app(self, import_name, name)
  331. else:
  332. for path in ("wsgi.py", "app.py"):
  333. import_name = prepare_import(path)
  334. app = locate_app(self, import_name, None, raise_if_not_found=False)
  335. if app:
  336. break
  337. if not app:
  338. raise NoAppException(
  339. "Could not locate a Flask application. You did not provide "
  340. 'the "FLASK_APP" environment variable, and a "wsgi.py" or '
  341. '"app.py" module was not found in the current directory.'
  342. )
  343. if self.set_debug_flag:
  344. # Update the app's debug flag through the descriptor so that
  345. # other values repopulate as well.
  346. app.debug = get_debug_flag()
  347. self._loaded_app = app
  348. return app
  349. pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
  350. def with_appcontext(f):
  351. """Wraps a callback so that it's guaranteed to be executed with the
  352. script's application context. If callbacks are registered directly
  353. to the ``app.cli`` object then they are wrapped with this function
  354. by default unless it's disabled.
  355. """
  356. @click.pass_context
  357. def decorator(__ctx, *args, **kwargs):
  358. with __ctx.ensure_object(ScriptInfo).load_app().app_context():
  359. return __ctx.invoke(f, *args, **kwargs)
  360. return update_wrapper(decorator, f)
  361. class AppGroup(click.Group):
  362. """This works similar to a regular click :class:`~click.Group` but it
  363. changes the behavior of the :meth:`command` decorator so that it
  364. automatically wraps the functions in :func:`with_appcontext`.
  365. Not to be confused with :class:`FlaskGroup`.
  366. """
  367. def command(self, *args, **kwargs):
  368. """This works exactly like the method of the same name on a regular
  369. :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
  370. unless it's disabled by passing ``with_appcontext=False``.
  371. """
  372. wrap_for_ctx = kwargs.pop("with_appcontext", True)
  373. def decorator(f):
  374. if wrap_for_ctx:
  375. f = with_appcontext(f)
  376. return click.Group.command(self, *args, **kwargs)(f)
  377. return decorator
  378. def group(self, *args, **kwargs):
  379. """This works exactly like the method of the same name on a regular
  380. :class:`click.Group` but it defaults the group class to
  381. :class:`AppGroup`.
  382. """
  383. kwargs.setdefault("cls", AppGroup)
  384. return click.Group.group(self, *args, **kwargs)
  385. class FlaskGroup(AppGroup):
  386. """Special subclass of the :class:`AppGroup` group that supports
  387. loading more commands from the configured Flask app. Normally a
  388. developer does not have to interface with this class but there are
  389. some very advanced use cases for which it makes sense to create an
  390. instance of this. see :ref:`custom-scripts`.
  391. :param add_default_commands: if this is True then the default run and
  392. shell commands will be added.
  393. :param add_version_option: adds the ``--version`` option.
  394. :param create_app: an optional callback that is passed the script info and
  395. returns the loaded app.
  396. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  397. files to set environment variables. Will also change the working
  398. directory to the directory containing the first file found.
  399. :param set_debug_flag: Set the app's debug flag based on the active
  400. environment
  401. .. versionchanged:: 1.0
  402. If installed, python-dotenv will be used to load environment variables
  403. from :file:`.env` and :file:`.flaskenv` files.
  404. """
  405. def __init__(
  406. self,
  407. add_default_commands=True,
  408. create_app=None,
  409. add_version_option=True,
  410. load_dotenv=True,
  411. set_debug_flag=True,
  412. **extra,
  413. ):
  414. params = list(extra.pop("params", None) or ())
  415. if add_version_option:
  416. params.append(version_option)
  417. AppGroup.__init__(self, params=params, **extra)
  418. self.create_app = create_app
  419. self.load_dotenv = load_dotenv
  420. self.set_debug_flag = set_debug_flag
  421. if add_default_commands:
  422. self.add_command(run_command)
  423. self.add_command(shell_command)
  424. self.add_command(routes_command)
  425. self._loaded_plugin_commands = False
  426. def _load_plugin_commands(self):
  427. if self._loaded_plugin_commands:
  428. return
  429. try:
  430. import pkg_resources
  431. except ImportError:
  432. self._loaded_plugin_commands = True
  433. return
  434. for ep in pkg_resources.iter_entry_points("flask.commands"):
  435. self.add_command(ep.load(), ep.name)
  436. self._loaded_plugin_commands = True
  437. def get_command(self, ctx, name):
  438. self._load_plugin_commands()
  439. # Look up built-in and plugin commands, which should be
  440. # available even if the app fails to load.
  441. rv = super().get_command(ctx, name)
  442. if rv is not None:
  443. return rv
  444. info = ctx.ensure_object(ScriptInfo)
  445. # Look up commands provided by the app, showing an error and
  446. # continuing if the app couldn't be loaded.
  447. try:
  448. return info.load_app().cli.get_command(ctx, name)
  449. except NoAppException as e:
  450. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  451. def list_commands(self, ctx):
  452. self._load_plugin_commands()
  453. # Start with the built-in and plugin commands.
  454. rv = set(super().list_commands(ctx))
  455. info = ctx.ensure_object(ScriptInfo)
  456. # Add commands provided by the app, showing an error and
  457. # continuing if the app couldn't be loaded.
  458. try:
  459. rv.update(info.load_app().cli.list_commands(ctx))
  460. except NoAppException as e:
  461. # When an app couldn't be loaded, show the error message
  462. # without the traceback.
  463. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  464. except Exception:
  465. # When any other errors occurred during loading, show the
  466. # full traceback.
  467. click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")
  468. return sorted(rv)
  469. def main(self, *args, **kwargs):
  470. # Set a global flag that indicates that we were invoked from the
  471. # command line interface. This is detected by Flask.run to make the
  472. # call into a no-op. This is necessary to avoid ugly errors when the
  473. # script that is loaded here also attempts to start a server.
  474. os.environ["FLASK_RUN_FROM_CLI"] = "true"
  475. if get_load_dotenv(self.load_dotenv):
  476. load_dotenv()
  477. obj = kwargs.get("obj")
  478. if obj is None:
  479. obj = ScriptInfo(
  480. create_app=self.create_app, set_debug_flag=self.set_debug_flag
  481. )
  482. kwargs["obj"] = obj
  483. kwargs.setdefault("auto_envvar_prefix", "FLASK")
  484. return super().main(*args, **kwargs)
  485. def _path_is_ancestor(path, other):
  486. """Take ``other`` and remove the length of ``path`` from it. Then join it
  487. to ``path``. If it is the original value, ``path`` is an ancestor of
  488. ``other``."""
  489. return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
  490. def load_dotenv(path=None):
  491. """Load "dotenv" files in order of precedence to set environment variables.
  492. If an env var is already set it is not overwritten, so earlier files in the
  493. list are preferred over later files.
  494. This is a no-op if `python-dotenv`_ is not installed.
  495. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
  496. :param path: Load the file at this location instead of searching.
  497. :return: ``True`` if a file was loaded.
  498. .. versionchanged:: 1.1.0
  499. Returns ``False`` when python-dotenv is not installed, or when
  500. the given path isn't a file.
  501. .. versionchanged:: 2.0
  502. When loading the env files, set the default encoding to UTF-8.
  503. .. versionadded:: 1.0
  504. """
  505. if dotenv is None:
  506. if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
  507. click.secho(
  508. " * Tip: There are .env or .flaskenv files present."
  509. ' Do "pip install python-dotenv" to use them.',
  510. fg="yellow",
  511. err=True,
  512. )
  513. return False
  514. # if the given path specifies the actual file then return True,
  515. # else False
  516. if path is not None:
  517. if os.path.isfile(path):
  518. return dotenv.load_dotenv(path, encoding="utf-8")
  519. return False
  520. new_dir = None
  521. for name in (".env", ".flaskenv"):
  522. path = dotenv.find_dotenv(name, usecwd=True)
  523. if not path:
  524. continue
  525. if new_dir is None:
  526. new_dir = os.path.dirname(path)
  527. dotenv.load_dotenv(path, encoding="utf-8")
  528. return new_dir is not None # at least one file was located and loaded
  529. def show_server_banner(env, debug, app_import_path, eager_loading):
  530. """Show extra startup messages the first time the server is run,
  531. ignoring the reloader.
  532. """
  533. if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
  534. return
  535. if app_import_path is not None:
  536. message = f" * Serving Flask app {app_import_path!r}"
  537. if not eager_loading:
  538. message += " (lazy loading)"
  539. click.echo(message)
  540. click.echo(f" * Environment: {env}")
  541. if env == "production":
  542. click.secho(
  543. " WARNING: This is a development server. Do not use it in"
  544. " a production deployment.",
  545. fg="red",
  546. )
  547. click.secho(" Use a production WSGI server instead.", dim=True)
  548. if debug is not None:
  549. click.echo(f" * Debug mode: {'on' if debug else 'off'}")
  550. class CertParamType(click.ParamType):
  551. """Click option type for the ``--cert`` option. Allows either an
  552. existing file, the string ``'adhoc'``, or an import for a
  553. :class:`~ssl.SSLContext` object.
  554. """
  555. name = "path"
  556. def __init__(self):
  557. self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)
  558. def convert(self, value, param, ctx):
  559. if ssl is None:
  560. raise click.BadParameter(
  561. 'Using "--cert" requires Python to be compiled with SSL support.',
  562. ctx,
  563. param,
  564. )
  565. try:
  566. return self.path_type(value, param, ctx)
  567. except click.BadParameter:
  568. value = click.STRING(value, param, ctx).lower()
  569. if value == "adhoc":
  570. try:
  571. import cryptography # noqa: F401
  572. except ImportError:
  573. raise click.BadParameter(
  574. "Using ad-hoc certificates requires the cryptography library.",
  575. ctx,
  576. param,
  577. ) from None
  578. return value
  579. obj = import_string(value, silent=True)
  580. if isinstance(obj, ssl.SSLContext):
  581. return obj
  582. raise
  583. def _validate_key(ctx, param, value):
  584. """The ``--key`` option must be specified when ``--cert`` is a file.
  585. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
  586. """
  587. cert = ctx.params.get("cert")
  588. is_adhoc = cert == "adhoc"
  589. is_context = ssl and isinstance(cert, ssl.SSLContext)
  590. if value is not None:
  591. if is_adhoc:
  592. raise click.BadParameter(
  593. 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
  594. )
  595. if is_context:
  596. raise click.BadParameter(
  597. 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param
  598. )
  599. if not cert:
  600. raise click.BadParameter('"--cert" must also be specified.', ctx, param)
  601. ctx.params["cert"] = cert, value
  602. else:
  603. if cert and not (is_adhoc or is_context):
  604. raise click.BadParameter('Required when using "--cert".', ctx, param)
  605. return value
  606. class SeparatedPathType(click.Path):
  607. """Click option type that accepts a list of values separated by the
  608. OS's path separator (``:``, ``;`` on Windows). Each value is
  609. validated as a :class:`click.Path` type.
  610. """
  611. def convert(self, value, param, ctx):
  612. items = self.split_envvar_value(value)
  613. super_convert = super().convert
  614. return [super_convert(item, param, ctx) for item in items]
  615. @click.command("run", short_help="Run a development server.")
  616. @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
  617. @click.option("--port", "-p", default=5000, help="The port to bind to.")
  618. @click.option(
  619. "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."
  620. )
  621. @click.option(
  622. "--key",
  623. type=click.Path(exists=True, dir_okay=False, resolve_path=True),
  624. callback=_validate_key,
  625. expose_value=False,
  626. help="The key file to use when specifying a certificate.",
  627. )
  628. @click.option(
  629. "--reload/--no-reload",
  630. default=None,
  631. help="Enable or disable the reloader. By default the reloader "
  632. "is active if debug is enabled.",
  633. )
  634. @click.option(
  635. "--debugger/--no-debugger",
  636. default=None,
  637. help="Enable or disable the debugger. By default the debugger "
  638. "is active if debug is enabled.",
  639. )
  640. @click.option(
  641. "--eager-loading/--lazy-loading",
  642. default=None,
  643. help="Enable or disable eager loading. By default eager "
  644. "loading is enabled if the reloader is disabled.",
  645. )
  646. @click.option(
  647. "--with-threads/--without-threads",
  648. default=True,
  649. help="Enable or disable multithreading.",
  650. )
  651. @click.option(
  652. "--extra-files",
  653. default=None,
  654. type=SeparatedPathType(),
  655. help=(
  656. "Extra files that trigger a reload on change. Multiple paths"
  657. f" are separated by {os.path.pathsep!r}."
  658. ),
  659. )
  660. @pass_script_info
  661. def run_command(
  662. info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files
  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. )
  688. @click.command("shell", short_help="Run a shell in the app context.")
  689. @with_appcontext
  690. def shell_command() -> None:
  691. """Run an interactive Python shell in the context of a given
  692. Flask application. The application will populate the default
  693. namespace of this shell according to its configuration.
  694. This is useful for executing small snippets of management code
  695. without having to manually configure the application.
  696. """
  697. import code
  698. from .globals import _app_ctx_stack
  699. app = _app_ctx_stack.top.app
  700. banner = (
  701. f"Python {sys.version} on {sys.platform}\n"
  702. f"App: {app.import_name} [{app.env}]\n"
  703. f"Instance: {app.instance_path}"
  704. )
  705. ctx: dict = {}
  706. # Support the regular Python interpreter startup script if someone
  707. # is using it.
  708. startup = os.environ.get("PYTHONSTARTUP")
  709. if startup and os.path.isfile(startup):
  710. with open(startup) as f:
  711. eval(compile(f.read(), startup, "exec"), ctx)
  712. ctx.update(app.make_shell_context())
  713. # Site, customize, or startup script can set a hook to call when
  714. # entering interactive mode. The default one sets up readline with
  715. # tab and history completion.
  716. interactive_hook = getattr(sys, "__interactivehook__", None)
  717. if interactive_hook is not None:
  718. try:
  719. import readline
  720. from rlcompleter import Completer
  721. except ImportError:
  722. pass
  723. else:
  724. # rlcompleter uses __main__.__dict__ by default, which is
  725. # flask.__main__. Use the shell context instead.
  726. readline.set_completer(Completer(ctx).complete)
  727. interactive_hook()
  728. code.interact(banner=banner, local=ctx)
  729. @click.command("routes", short_help="Show the routes for the app.")
  730. @click.option(
  731. "--sort",
  732. "-s",
  733. type=click.Choice(("endpoint", "methods", "rule", "match")),
  734. default="endpoint",
  735. help=(
  736. 'Method to sort routes by. "match" is the order that Flask will match '
  737. "routes when dispatching a request."
  738. ),
  739. )
  740. @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
  741. @with_appcontext
  742. def routes_command(sort: str, all_methods: bool) -> None:
  743. """Show all registered routes with endpoints and methods."""
  744. rules = list(current_app.url_map.iter_rules())
  745. if not rules:
  746. click.echo("No routes were registered.")
  747. return
  748. ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))
  749. if sort in ("endpoint", "rule"):
  750. rules = sorted(rules, key=attrgetter(sort))
  751. elif sort == "methods":
  752. rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore
  753. rule_methods = [
  754. ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore
  755. for rule in rules
  756. ]
  757. headers = ("Endpoint", "Methods", "Rule")
  758. widths = (
  759. max(len(rule.endpoint) for rule in rules),
  760. max(len(methods) for methods in rule_methods),
  761. max(len(rule.rule) for rule in rules),
  762. )
  763. widths = [max(len(h), w) for h, w in zip(headers, widths)]
  764. row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)
  765. click.echo(row.format(*headers).strip())
  766. click.echo(row.format(*("-" * width for width in widths)))
  767. for rule, methods in zip(rules, rule_methods):
  768. click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())
  769. cli = FlaskGroup(
  770. help="""\
  771. A general utility script for Flask applications.
  772. Provides commands from Flask, extensions, and the application. Loads the
  773. application defined in the FLASK_APP environment variable, or from a wsgi.py
  774. file. Setting the FLASK_ENV environment variable to 'development' will enable
  775. debug mode.
  776. \b
  777. {prefix}{cmd} FLASK_APP=hello.py
  778. {prefix}{cmd} FLASK_ENV=development
  779. {prefix}flask run
  780. """.format(
  781. cmd="export" if os.name == "posix" else "set",
  782. prefix="$ " if os.name == "posix" else "> ",
  783. )
  784. )
  785. def main() -> None:
  786. if int(click.__version__[0]) < 8:
  787. warnings.warn(
  788. "Using the `flask` cli with Click 7 is deprecated and"
  789. " will not be supported starting with Flask 2.1."
  790. " Please upgrade to Click 8 as soon as possible.",
  791. DeprecationWarning,
  792. )
  793. # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed
  794. cli.main(args=sys.argv[1:])
  795. if __name__ == "__main__":
  796. main()