Implemented simplified CLI interface
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 92f63a1 · Browse files · 5 files·+51 added−91 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+51 added−91 removed
- tests:+1 added−2 removed
- other:+50 added−89 removed
Provenance
- Commit
523e271- Tree
d4cff6d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
92f63a1
5 files changed+51 added−91 removed
modified:flask/app.py+3 added-2 removed
20 unmodified lines21 from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest, default_exceptions23 24 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25- locked_cached_property, _endpoint_from_view_func, find_package25+ locked_cached_property, _endpoint_from_view_func, find_package, \26+ get_debug_flag27 from . import json, cli28 from .wrappers import Request, Response29 from .config import ConfigAttribute, Config30 from .ctx import RequestContext, AppContext, _AppCtxGlobals258 unmodified lines289 )290 291 #: Default configuration parameters.292 default_config = ImmutableDict({292- 'DEBUG': False,293+ 'DEBUG': get_debug_flag(default=False),294 'TESTING': False,295 'PROPAGATE_EXCEPTIONS': None,296 'PRESERVE_CONTEXT_ON_EXCEPTION': None,297 'SECRET_KEY': None,1709 unmodified linesmodified:flask/cli.py+39 added-85 removed
15 unmodified lines16 17 import click18 19 from ._compat import iteritems, reraise20+from .helpers import get_debug_flag21 22 23 class NoAppException(click.UsageError):24 """Raised if an application cannot be found or loaded."""73 unmodified lines98 99 return app100 101 102+def find_default_import_path():103+ app = os.environ.get('FLASK_APP')104+ if app is None:105+ return106+ if os.path.isfile(app):107+ return prepare_exec_for_file(app)108+ return app109+110+111 class DispatchingApp(object):112 """Special application that dispatches to a flask application which113 is imported by name in a background thread. If an error happens114 it is is recorded and shows as part of the WSGI handling which in case52 unmodified lines167 necessary to interface with as it's used internally in the dispatching168 to click.169 """170 161- def __init__(self, app_import_path=None, debug=None, create_app=None):162- #: The application import path163- self.app_import_path = app_import_path164- #: The debug flag. If this is not None, the application will165- #: automatically have it's debug flag overridden with this value.166- self.debug = debug171+ def __init__(self, app_import_path=None, create_app=None):172+ if create_app is None:173+ if app_import_path is None:174+ app_import_path = find_default_import_path()175+ self.app_import_path = app_import_path176+ else:177+ self.app_import_path = None178 #: Optionally a function that is passed the script info to create179 #: the instance of the application.180 self.create_app = create_app181 #: A dictionary with arbitrary data that can be associated with13 unmodified lines195 rv = self.create_app(self)196 else:197 if self.app_import_path is None:198 raise NoAppException('Could not locate Flask application. '188- 'You did not provide FLASK_APP or the '189- '--app parameter.')199+ 'You did not provide the FLASK_APP '200+ 'environment variable.')201 rv = locate_app(self.app_import_path)202+ debug = get_debug_flag()191- if self.debug is not None:192- rv.debug = self.debug203+ if debug is not None:204+ rv.debug = debug205 self._loaded_app = rv206 return rv207 208 12 unmodified lines221 return __ctx.invoke(f, *args, **kwargs)222 return update_wrapper(decorator, f)223 224 213-def set_debug_value(ctx, param, value):214- ctx.ensure_object(ScriptInfo).debug = value215-216-217-def set_app_value(ctx, param, value):218- if value is not None:219- if os.path.isfile(value):220- value = prepare_exec_for_file(value)221- elif '.' not in sys.path:222- sys.path.insert(0, '.')223- ctx.ensure_object(ScriptInfo).app_import_path = value224-225-226-debug_option = click.Option(['--debug/--no-debug'],227- help='Enable or disable debug mode.',228- default=None, callback=set_debug_value)229-230-231-app_option = click.Option(['-a', '--app'],232- help='The application to run',233- callback=set_app_value, is_eager=True)234-235-225 class AppGroup(click.Group):226 """This works similar to a regular click :class:`~click.Group` but it227 changes the behavior of the :meth:`command` decorator so that it228 automatically wraps the functions in :func:`with_appcontext`.32 unmodified lines261 For information as of why this is useful see :ref:`custom-scripts`.262 263 :param add_default_commands: if this is True then the default run and264 shell commands wil be added.276- :param add_app_option: adds the default :option:`--app` option. This gets277- automatically disabled if a `create_app`278- callback is defined.279- :param add_debug_option: adds the default :option:`--debug` option.265 :param create_app: an optional callback that is passed the script info266 and returns the loaded app.267 """268 284- def __init__(self, add_default_commands=True, add_app_option=None,285- add_debug_option=True, create_app=None, **extra):286- params = list(extra.pop('params', None) or ())287- if add_app_option is None:288- add_app_option = create_app is None289- if add_app_option:290- params.append(app_option)291- if add_debug_option:292- params.append(debug_option)293-294- AppGroup.__init__(self, params=params, **extra)269+ def __init__(self, add_default_commands=True, create_app=None, **extra):270+ AppGroup.__init__(self, **extra)271 self.create_app = create_app272 273 if add_default_commands:274 self.add_command(run_command)42 unmodified lines317 kwargs.setdefault('auto_envvar_prefix', 'FLASK')318 return AppGroup.main(self, *args, **kwargs)319 320 345-def script_info_option(*args, **kwargs):346- """This decorator works exactly like :func:`click.option` but is eager347- by default and stores the value in the :attr:`ScriptInfo.data`. This348- is useful to further customize an application factory in very complex349- situations.350-351- :param script_info_key: this is a mandatory keyword argument which352- defines under which data key the value should353- be stored.354- """355- try:356- key = kwargs.pop('script_info_key')357- except LookupError:358- raise TypeError('script_info_key not provided.')359-360- real_callback = kwargs.get('callback')361- def callback(ctx, param, value):362- if real_callback is not None:363- value = real_callback(ctx, value)364- ctx.ensure_object(ScriptInfo).data[key] = value365- return value366-367- kwargs['callback'] = callback368- kwargs.setdefault('is_eager', True)369- return click.option(*args, **kwargs)370-371-321 @click.command('run', short_help='Runs a development server.')322 @click.option('--host', '-h', default='127.0.0.1',323 help='The interface to bind to.')324 @click.option('--port', '-p', default=5000,23 unmodified lines348 The reloader and debugger are by default enabled if the debug flag of349 Flask is enabled and disabled otherwise.350 """351 from werkzeug.serving import run_simple352+353+ debug = get_debug_flag()354 if reload is None:404- reload = info.debug355+ reload = bool(debug)356 if debugger is None:406- debugger = info.debug357+ debugger = bool(debug)358 if eager_loading is None:359 eager_loading = not reload360 361 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)6 unmodified lines368 # import path because the app was loaded through a callback then369 # we won't print anything.370 if info.app_import_path is not None:371 print(' * Serving Flask app "%s"' % info.app_import_path)421- if info.debug is not None:422- print(' * Forcing debug %s' % (info.debug and 'on' or 'off'))372 373 run_simple(host, port, app, use_reloader=reload,425- use_debugger=debugger, threaded=with_threads,426- passthrough_errors=True)374+ use_debugger=debugger, threaded=with_threads)375 376 377 @click.command('shell', short_help='Runs a shell in the app context.')378 @with_appcontext32 unmodified lines411 cli = FlaskGroup(help="""\412 This shell command acts as general utility script for Flask applications.413 414 It loads the application configured (either through the FLASK_APP environment467-variable or the --app parameter) and then provides commands either provided468-by the application or Flask itself.415+variable) and then provides commands either provided by the application or416+Flask itself.417 418 The most useful commands are the "run" and "shell" command.419 420 Example usage:421 474- flask --app=hello --debug run475-""")422+\b423+ %(prefix)s%(cmd)s FLASK_APP=hello424+ %(prefix)s%(cmd)s FLASK_DEBUG=1425+ %(prefix)sflask run426+""" % {427+ 'cmd': os.name == 'posix' and 'export' or 'set',428+ 'prefix': os.name == 'posix' and '$ ' or '',429+})430 431 432 def main(as_module=False):433 this_module = __package__ + '.cli'20 unmodified linesmodified:flask/helpers.py+7 added-1 removed
12 unmodified lines13 import sys14 import pkgutil15 import posixpath16 import mimetypes17-from datetime import timedelta17 from time import time18 from zlib import adler3219 from threading import RLock20 from werkzeug.routing import BuildError31 unmodified lines52 _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]53 if sep not in (None, '/'))54 55 56+def get_debug_flag(default=None):57+ val = os.environ.get('FLASK_DEBUG')58+ if not val:59+ return default60+ return val not in ('0', 'false', 'no')61+62+63 def _endpoint_from_view_func(view_func):64 """Internal helper that returns the default endpoint for a given65 function. This always is the function name.66 """855 unmodified linesmodified:tests/test_cli.py+1 added-2 removed
17 unmodified lines18 from click.testing import CliRunner19 from flask import Flask, current_app20 21 from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \22- find_best_app, locate_app, script_info_option, with_appcontext22+ find_best_app, locate_app, with_appcontext23 24 25 def test_cli_name(test_apps):26 """Make sure the CLI object's name is the app's name and not the app itself"""95 unmodified lines122 def create_app(info):123 return Flask("flaskgroup")124 125 @click.group(cls=FlaskGroup, create_app=create_app)126- @script_info_option('--config', script_info_key='config')126 def cli(**params):127 pass128 129 @cli.command()7 unmodified linesmodified:Makefile+1 added-1 removed
1 unmodified line2 3 all: clean-pyc test4 5 test:6- py.test tests examples6+ FLASK_DEBUG= py.test tests examples7 8 tox-test:9 tox10 33 unmodified lines