Skip to content
Myr

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

5 files+51 added−91 removed

modified:flask/app.py+3 added-2 removed
20 unmodified lines
21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest, default_exceptions2324from .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_flag27from . import json, cli28from .wrappers import Request, Response29from .config import ConfigAttribute, Config30from .ctx import RequestContext, AppContext, _AppCtxGlobals
258 unmodified lines
289 )290291 #: 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 lines
modified:flask/cli.py+39 added-85 removed
15 unmodified lines
1617import click1819from ._compat import iteritems, reraise20from .helpers import get_debug_flag212223class NoAppException(click.UsageError):24 """Raised if an application cannot be found or loaded."""
73 unmodified lines
9899 return app100101102def 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 app109110111class 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 case
52 unmodified lines
167 necessary to interface with as it's used internally in the dispatching168 to click.169 """170161 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 with
13 unmodified lines
195 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 rv207208
12 unmodified lines
221 return __ctx.invoke(f, *args, **kwargs)222 return update_wrapper(decorator, f)223224213def set_debug_value(ctx, param, value):214 ctx.ensure_object(ScriptInfo).debug = value215216217def 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 = value224225226debug_option = click.Option(['--debug/--no-debug'],227 help='Enable or disable debug mode.',228 default=None, callback=set_debug_value)229230231app_option = click.Option(['-a', '--app'],232 help='The application to run',233 callback=set_app_value, is_eager=True)234235225class 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 lines
261 For information as of why this is useful see :ref:`custom-scripts`.262263 :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 """268284 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)293294 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_app272273 if add_default_commands:274 self.add_command(run_command)
42 unmodified lines
317 kwargs.setdefault('auto_envvar_prefix', 'FLASK')318 return AppGroup.main(self, *args, **kwargs)319320345def 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.350351 :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.')359360 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 value366367 kwargs['callback'] = callback368 kwargs.setdefault('is_eager', True)369 return click.option(*args, **kwargs)370371321@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 lines
348 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_simple352353 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 reload360361 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
6 unmodified lines
368 # 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'))372373 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)375376377@click.command('shell', short_help='Runs a shell in the app context.')378@with_appcontext
32 unmodified lines
411cli = FlaskGroup(help="""\412This shell command acts as general utility script for Flask applications.413414It loads the application configured (either through the FLASK_APP environment467variable or the --app parameter) and then provides commands either provided468by the application or Flask itself.415variable) and then provides commands either provided by the application or416Flask itself.417418The most useful commands are the "run" and "shell" command.419420Example usage:421474 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})430431432def main(as_module=False):433 this_module = __package__ + '.cli'
20 unmodified lines
modified:flask/helpers.py+7 added-1 removed
12 unmodified lines
13import sys14import pkgutil15import posixpath16import mimetypes17from datetime import timedelta17from time import time18from zlib import adler3219from threading import RLock20from werkzeug.routing import BuildError
31 unmodified lines
52_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]53 if sep not in (None, '/'))545556def 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')616263def _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 lines
modified:tests/test_cli.py+1 added-2 removed
17 unmodified lines
18from click.testing import CliRunner19from flask import Flask, current_app2021from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \22 find_best_app, locate_app, script_info_option, with_appcontext22 find_best_app, locate_app, with_appcontext232425def 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 lines
122 def create_app(info):123 return Flask("flaskgroup")124125 @click.group(cls=FlaskGroup, create_app=create_app)126 @script_info_option('--config', script_info_key='config')126 def cli(**params):127 pass128129 @cli.command()
7 unmodified lines
modified:Makefile+1 added-1 removed
1 unmodified line
23all: clean-pyc test45test:6 py.test tests examples6 FLASK_DEBUG= py.test tests examples78tox-test:9 tox10
33 unmodified lines