You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

995 lines
31KB

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