cli.py 29 KB

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