1
0

cli.py 30 KB

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