cli.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.cli
  4. ~~~~~~~~~
  5. A simple command line application to run flask apps.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import os
  10. import sys
  11. from threading import Lock, Thread
  12. from functools import update_wrapper
  13. import click
  14. from ._compat import iteritems, reraise
  15. from .helpers import get_debug_flag
  16. class NoAppException(click.UsageError):
  17. """Raised if an application cannot be found or loaded."""
  18. def find_best_app(module):
  19. """Given a module instance this tries to find the best possible
  20. application in the module or raises an exception.
  21. """
  22. from . import Flask
  23. # Search for the most common names first.
  24. for attr_name in 'app', 'application':
  25. app = getattr(module, attr_name, None)
  26. if app is not None and isinstance(app, Flask):
  27. return app
  28. # Otherwise find the only object that is a Flask instance.
  29. matches = [v for k, v in iteritems(module.__dict__)
  30. if isinstance(v, Flask)]
  31. if len(matches) == 1:
  32. return matches[0]
  33. raise NoAppException('Failed to find application in module "%s". Are '
  34. 'you sure it contains a Flask application? Maybe '
  35. 'you wrapped it in a WSGI middleware or you are '
  36. 'using a factory function.' % module.__name__)
  37. def prepare_exec_for_file(filename):
  38. """Given a filename this will try to calculate the python path, add it
  39. to the search path and return the actual module name that is expected.
  40. """
  41. module = []
  42. # Chop off file extensions or package markers
  43. if os.path.split(filename)[1] == '__init__.py':
  44. filename = os.path.dirname(filename)
  45. elif filename.endswith('.py'):
  46. filename = filename[:-3]
  47. else:
  48. raise NoAppException('The file provided (%s) does exist but is not a '
  49. 'valid Python file. This means that it cannot '
  50. 'be used as application. Please change the '
  51. 'extension to .py' % filename)
  52. filename = os.path.realpath(filename)
  53. dirpath = filename
  54. while 1:
  55. dirpath, extra = os.path.split(dirpath)
  56. module.append(extra)
  57. if not os.path.isfile(os.path.join(dirpath, '__init__.py')):
  58. break
  59. sys.path.insert(0, dirpath)
  60. return '.'.join(module[::-1])
  61. def locate_app(app_id):
  62. """Attempts to locate the application."""
  63. __traceback_hide__ = True
  64. if ':' in app_id:
  65. module, app_obj = app_id.split(':', 1)
  66. else:
  67. module = app_id
  68. app_obj = None
  69. __import__(module)
  70. mod = sys.modules[module]
  71. if app_obj is None:
  72. app = find_best_app(mod)
  73. else:
  74. app = getattr(mod, app_obj, None)
  75. if app is None:
  76. raise RuntimeError('Failed to find application in module "%s"'
  77. % module)
  78. return app
  79. def find_default_import_path():
  80. app = os.environ.get('FLASK_APP')
  81. if app is None:
  82. return
  83. if os.path.isfile(app):
  84. return prepare_exec_for_file(app)
  85. return app
  86. class DispatchingApp(object):
  87. """Special application that dispatches to a flask application which
  88. is imported by name in a background thread. If an error happens
  89. it is is recorded and shows as part of the WSGI handling which in case
  90. of the Werkzeug debugger means that it shows up in the browser.
  91. """
  92. def __init__(self, loader, use_eager_loading=False):
  93. self.loader = loader
  94. self._app = None
  95. self._lock = Lock()
  96. self._bg_loading_exc_info = None
  97. if use_eager_loading:
  98. self._load_unlocked()
  99. else:
  100. self._load_in_background()
  101. def _load_in_background(self):
  102. def _load_app():
  103. __traceback_hide__ = True
  104. with self._lock:
  105. try:
  106. self._load_unlocked()
  107. except Exception:
  108. self._bg_loading_exc_info = sys.exc_info()
  109. t = Thread(target=_load_app, args=())
  110. t.start()
  111. def _flush_bg_loading_exception(self):
  112. __traceback_hide__ = True
  113. exc_info = self._bg_loading_exc_info
  114. if exc_info is not None:
  115. self._bg_loading_exc_info = None
  116. reraise(*exc_info)
  117. def _load_unlocked(self):
  118. __traceback_hide__ = True
  119. self._app = rv = self.loader()
  120. self._bg_loading_exc_info = None
  121. return rv
  122. def __call__(self, environ, start_response):
  123. __traceback_hide__ = True
  124. if self._app is not None:
  125. return self._app(environ, start_response)
  126. self._flush_bg_loading_exception()
  127. with self._lock:
  128. if self._app is not None:
  129. rv = self._app
  130. else:
  131. rv = self._load_unlocked()
  132. return rv(environ, start_response)
  133. class ScriptInfo(object):
  134. """Help object to deal with Flask applications. This is usually not
  135. necessary to interface with as it's used internally in the dispatching
  136. to click. In future versions of Flask this object will most likely play
  137. a bigger role. Typically it's created automatically by the
  138. :class:`FlaskGroup` but you can also manually create it and pass it
  139. onwards as click object.
  140. """
  141. def __init__(self, app_import_path=None, create_app=None):
  142. if create_app is None:
  143. if app_import_path is None:
  144. app_import_path = find_default_import_path()
  145. self.app_import_path = app_import_path
  146. else:
  147. app_import_path = None
  148. #: Optionally the import path for the Flask application.
  149. self.app_import_path = app_import_path
  150. #: Optionally a function that is passed the script info to create
  151. #: the instance of the application.
  152. self.create_app = create_app
  153. #: A dictionary with arbitrary data that can be associated with
  154. #: this script info.
  155. self.data = {}
  156. self._loaded_app = None
  157. def load_app(self):
  158. """Loads the Flask app (if not yet loaded) and returns it. Calling
  159. this multiple times will just result in the already loaded app to
  160. be returned.
  161. """
  162. __traceback_hide__ = True
  163. if self._loaded_app is not None:
  164. return self._loaded_app
  165. if self.create_app is not None:
  166. rv = self.create_app(self)
  167. else:
  168. if not self.app_import_path:
  169. raise NoAppException(
  170. 'Could not locate Flask application. You did not provide '
  171. 'the FLASK_APP environment variable.\n\nFor more '
  172. 'information see '
  173. 'http://flask.pocoo.org/docs/latest/quickstart/')
  174. rv = locate_app(self.app_import_path)
  175. debug = get_debug_flag()
  176. if debug is not None:
  177. rv.debug = debug
  178. self._loaded_app = rv
  179. return rv
  180. pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
  181. def with_appcontext(f):
  182. """Wraps a callback so that it's guaranteed to be executed with the
  183. script's application context. If callbacks are registered directly
  184. to the ``app.cli`` object then they are wrapped with this function
  185. by default unless it's disabled.
  186. """
  187. @click.pass_context
  188. def decorator(__ctx, *args, **kwargs):
  189. with __ctx.ensure_object(ScriptInfo).load_app().app_context():
  190. return __ctx.invoke(f, *args, **kwargs)
  191. return update_wrapper(decorator, f)
  192. class AppGroup(click.Group):
  193. """This works similar to a regular click :class:`~click.Group` but it
  194. changes the behavior of the :meth:`command` decorator so that it
  195. automatically wraps the functions in :func:`with_appcontext`.
  196. Not to be confused with :class:`FlaskGroup`.
  197. """
  198. def command(self, *args, **kwargs):
  199. """This works exactly like the method of the same name on a regular
  200. :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
  201. unless it's disabled by passing ``with_appcontext=False``.
  202. """
  203. wrap_for_ctx = kwargs.pop('with_appcontext', True)
  204. def decorator(f):
  205. if wrap_for_ctx:
  206. f = with_appcontext(f)
  207. return click.Group.command(self, *args, **kwargs)(f)
  208. return decorator
  209. def group(self, *args, **kwargs):
  210. """This works exactly like the method of the same name on a regular
  211. :class:`click.Group` but it defaults the group class to
  212. :class:`AppGroup`.
  213. """
  214. kwargs.setdefault('cls', AppGroup)
  215. return click.Group.group(self, *args, **kwargs)
  216. class FlaskGroup(AppGroup):
  217. """Special subclass of the :class:`AppGroup` group that supports
  218. loading more commands from the configured Flask app. Normally a
  219. developer does not have to interface with this class but there are
  220. some very advanced use cases for which it makes sense to create an
  221. instance of this.
  222. For information as of why this is useful see :ref:`custom-scripts`.
  223. :param add_default_commands: if this is True then the default run and
  224. shell commands wil be added.
  225. :param create_app: an optional callback that is passed the script info
  226. and returns the loaded app.
  227. """
  228. def __init__(self, add_default_commands=True, create_app=None, **extra):
  229. AppGroup.__init__(self, **extra)
  230. self.create_app = create_app
  231. if add_default_commands:
  232. self.add_command(run_command)
  233. self.add_command(shell_command)
  234. self._loaded_plugin_commands = False
  235. def _load_plugin_commands(self):
  236. if self._loaded_plugin_commands:
  237. return
  238. try:
  239. import pkg_resources
  240. except ImportError:
  241. self._loaded_plugin_commands = True
  242. return
  243. for ep in pkg_resources.iter_entry_points('flask.commands'):
  244. self.add_command(ep.load(), ep.name)
  245. self._loaded_plugin_commands = True
  246. def get_command(self, ctx, name):
  247. self._load_plugin_commands()
  248. # We load built-in commands first as these should always be the
  249. # same no matter what the app does. If the app does want to
  250. # override this it needs to make a custom instance of this group
  251. # and not attach the default commands.
  252. #
  253. # This also means that the script stays functional in case the
  254. # application completely fails.
  255. rv = AppGroup.get_command(self, ctx, name)
  256. if rv is not None:
  257. return rv
  258. info = ctx.ensure_object(ScriptInfo)
  259. try:
  260. rv = info.load_app().cli.get_command(ctx, name)
  261. if rv is not None:
  262. return rv
  263. except NoAppException:
  264. pass
  265. def list_commands(self, ctx):
  266. self._load_plugin_commands()
  267. # The commands available is the list of both the application (if
  268. # available) plus the builtin commands.
  269. rv = set(click.Group.list_commands(self, ctx))
  270. info = ctx.ensure_object(ScriptInfo)
  271. try:
  272. rv.update(info.load_app().cli.list_commands(ctx))
  273. except Exception:
  274. # Here we intentionally swallow all exceptions as we don't
  275. # want the help page to break if the app does not exist.
  276. # If someone attempts to use the command we try to create
  277. # the app again and this will give us the error.
  278. pass
  279. return sorted(rv)
  280. def main(self, *args, **kwargs):
  281. obj = kwargs.get('obj')
  282. if obj is None:
  283. obj = ScriptInfo(create_app=self.create_app)
  284. kwargs['obj'] = obj
  285. kwargs.setdefault('auto_envvar_prefix', 'FLASK')
  286. return AppGroup.main(self, *args, **kwargs)
  287. @click.command('run', short_help='Runs a development server.')
  288. @click.option('--host', '-h', default='127.0.0.1',
  289. help='The interface to bind to.')
  290. @click.option('--port', '-p', default=5000,
  291. help='The port to bind to.')
  292. @click.option('--reload/--no-reload', default=None,
  293. help='Enable or disable the reloader. By default the reloader '
  294. 'is active if debug is enabled.')
  295. @click.option('--debugger/--no-debugger', default=None,
  296. help='Enable or disable the debugger. By default the debugger '
  297. 'is active if debug is enabled.')
  298. @click.option('--eager-loading/--lazy-loader', default=None,
  299. help='Enable or disable eager loading. By default eager '
  300. 'loading is enabled if the reloader is disabled.')
  301. @click.option('--with-threads/--without-threads', default=False,
  302. help='Enable or disable multithreading.')
  303. @pass_script_info
  304. def run_command(info, host, port, reload, debugger, eager_loading,
  305. with_threads):
  306. """Runs a local development server for the Flask application.
  307. This local server is recommended for development purposes only but it
  308. can also be used for simple intranet deployments. By default it will
  309. not support any sort of concurrency at all to simplify debugging. This
  310. can be changed with the --with-threads option which will enable basic
  311. multithreading.
  312. The reloader and debugger are by default enabled if the debug flag of
  313. Flask is enabled and disabled otherwise.
  314. """
  315. from werkzeug.serving import run_simple
  316. debug = get_debug_flag()
  317. if reload is None:
  318. reload = bool(debug)
  319. if debugger is None:
  320. debugger = bool(debug)
  321. if eager_loading is None:
  322. eager_loading = not reload
  323. app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  324. # Extra startup messages. This depends a but on Werkzeug internals to
  325. # not double execute when the reloader kicks in.
  326. if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
  327. # If we have an import path we can print it out now which can help
  328. # people understand what's being served. If we do not have an
  329. # import path because the app was loaded through a callback then
  330. # we won't print anything.
  331. if info.app_import_path is not None:
  332. print(' * Serving Flask app "%s"' % info.app_import_path)
  333. if debug is not None:
  334. print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))
  335. run_simple(host, port, app, use_reloader=reload,
  336. use_debugger=debugger, threaded=with_threads)
  337. @click.command('shell', short_help='Runs a shell in the app context.')
  338. @with_appcontext
  339. def shell_command():
  340. """Runs an interactive Python shell in the context of a given
  341. Flask application. The application will populate the default
  342. namespace of this shell according to it's configuration.
  343. This is useful for executing small snippets of management code
  344. without having to manually configuring the application.
  345. """
  346. import code
  347. from flask.globals import _app_ctx_stack
  348. app = _app_ctx_stack.top.app
  349. banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (
  350. sys.version,
  351. sys.platform,
  352. app.import_name,
  353. app.debug and ' [debug]' or '',
  354. app.instance_path,
  355. )
  356. ctx = {}
  357. # Support the regular Python interpreter startup script if someone
  358. # is using it.
  359. startup = os.environ.get('PYTHONSTARTUP')
  360. if startup and os.path.isfile(startup):
  361. with open(startup, 'r') as f:
  362. eval(compile(f.read(), startup, 'exec'), ctx)
  363. ctx.update(app.make_shell_context())
  364. code.interact(banner=banner, local=ctx)
  365. cli = FlaskGroup(help="""\
  366. This shell command acts as general utility script for Flask applications.
  367. It loads the application configured (either through the FLASK_APP environment
  368. variable) and then provides commands either provided by the application or
  369. Flask itself.
  370. The most useful commands are the "run" and "shell" command.
  371. Example usage:
  372. \b
  373. %(prefix)s%(cmd)s FLASK_APP=hello
  374. %(prefix)s%(cmd)s FLASK_DEBUG=1
  375. %(prefix)sflask run
  376. """ % {
  377. 'cmd': os.name == 'posix' and 'export' or 'set',
  378. 'prefix': os.name == 'posix' and '$ ' or '',
  379. })
  380. def main(as_module=False):
  381. this_module = __package__ + '.cli'
  382. args = sys.argv[1:]
  383. if as_module:
  384. if sys.version_info >= (2, 7):
  385. name = 'python -m ' + this_module.rsplit('.', 1)[0]
  386. else:
  387. name = 'python -m ' + this_module
  388. # This module is always executed as "python -m flask.run" and as such
  389. # we need to ensure that we restore the actual command line so that
  390. # the reloader can properly operate.
  391. sys.argv = ['-m', this_module] + sys.argv[1:]
  392. else:
  393. name = None
  394. cli.main(args=args, prog_name=name)
  395. if __name__ == '__main__':
  396. main(as_module=True)