Further refactored script system to allow more customization for special apps.
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 ed7b4cc · Browse files · 1 file·+115 added−73 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+115 added−73 removed
- other:+115 added−73 removed
Provenance
- Commit
81576c2- Tree
555ede1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ed7b4cc
1 file changed+115 added−73 removed
modified:flask/cli.py+115 added-73 removed
142 unmodified lines143 necessary to interface with as it's used internally in the dispatching144 to click.145 """146 147- def __init__(self, app_import_path=None, debug=None, load_callback=None):147+ def __init__(self, app_import_path=None, debug=None, create_app=None):148 self.app_import_path = app_import_path149 self.debug = debug150- self.load_callback = load_callback150+ self.create_app = create_app151 self._loaded_app = None152 153- def get_app_import_path(self):154- """Return the actual application import path or fails if it is155- not yet set.156- """157- if self.app_import_path is not None:158- return self.app_import_path159- _no_such_app()160-153 def load_app(self):162- """Loads the app (if not yet loaded) and returns it."""154+ """Loads the Flask app (if not yet loaded) and returns it."""155 if self._loaded_app is not None:156 return self._loaded_app165- if self.load_callback is not None:166- rv = self.load_callback()157+ if self.create_app is not None:158+ rv = self.create_app(self)159 else:160+ if self.app_import_path is None:161+ _no_such_app()168- rv = locate_app(self.get_app_import_path(), self.debug)162+ rv = locate_app(self.app_import_path, self.debug)163 self._loaded_app = rv164 return rv165 166 def make_wsgi_app(self, use_eager_loading=False):173- """Returns a WSGI app that loads the actual application at a174- later stage.167+ """Returns a WSGI app that loads the actual application at a later168+ stage (on first request). This has the advantage over169+ :meth:`load_app` that if used with a WSGI server, it will allow170+ the server to intercept errors later during request handling171+ instead of dying a horrible death.172+173+ If eager loading is disabled the loading will happen immediately.174 """175 if self.app_import_path is not None:176 def loader():177 return locate_app(self.app_import_path, self.debug)178 else:180- if self.load_callback is None:179+ if self.create_app is None:180 _no_such_app()181 def loader():183- return self.load_callback()182+ return self.create_app(self)183 return DispatchingApp(loader, use_eager_loading=use_eager_loading)184 185 @contextmanager186 def conditional_context(self, with_context=True):188- """Creates an application context or not, depending on the189- given parameter but always works as context manager.187+ """Creates an application context or not, depending on the given188+ parameter but always works as context manager. This is just a189+ shortcut for a common operation.190 """191 if with_context:192- with self.load_app().app_context() as ctx:192+ with self.load_app(self).app_context() as ctx:193 yield ctx194 else:195 yield None196 197 198+#: A special decorator that informs a click callback to be passed the199+#: script info object as first argument. This is normally not useful200+#: unless you implement very special commands like the run command which201+#: does not want the application to be loaded yet. This can be combined202+#: with the :func:`without_appcontext` decorator.203 pass_script_info = click.make_pass_decorator(ScriptInfo)204 205 206 def without_appcontext(f):5 unmodified lines212 f.__flask_without_appcontext__ = True213 return f214 215 211-class ContextGroupMixin(object):216+class FlaskGroup(click.Group):217+ """Special subclass of the a regular click group that supports218+ loading more commands from the configured Flask app. Normally a219+ developer does not have to interface with this class but there are220+ some very advanced usecases for which it makes sense to create an221+ instance of this.222 223+ :param add_default_options: if this is True the app and debug option224+ is automatically added.225+ """226+227+ def __init__(self, add_default_options=True,228+ add_default_commands=True,229+ create_app=None, **extra):230+ click.Group.__init__(self, **extra)231+ self.create_app = create_app232+ if add_default_options:233+ self.add_app_option()234+ self.add_debug_option()235+ if add_default_commands:236+ self.add_command(run_command)237+ self.add_command(shell_command)238+239+ def add_app_option(self):240+ """Adds an option to the default command that defines an import241+ path that points to an application.242+ """243+ def set_app_id(ctx, value):244+ if value is not None:245+ if os.path.isfile(value):246+ value = prepare_exec_for_file(value)247+ elif '.' not in sys.path:248+ sys.path.insert(0, '.')249+ ctx.ensure_object(ScriptInfo).app_import_path = value250+251+ self.params.append(click.Option(['-a', '--app'],252+ help='The application to run',253+ callback=set_app_id, is_eager=True))254+255+ def add_debug_option(self):256+ """Adds an option that controls the debug flag."""257+ def set_debug(ctx, value):258+ ctx.ensure_object(ScriptInfo).debug = value259+260+ self.params.append(click.Option(['--debug/--no-debug'],261+ help='Enable or disable debug mode.',262+ default=None, callback=set_debug))263+264 def get_command(self, ctx, name):214- info = ctx.find_object(ScriptInfo)265+ info = ctx.ensure_object(ScriptInfo)266 # Find the command in the application first, if we can find it.267 # If the app is not available, we just ignore this silently.268 try:269 rv = info.load_app().cli.get_command(ctx, name)270 if rv is not None:271 return rv272 except NoAppException:273 pass223- return super(ContextGroupMixin, self).get_command(ctx, name)274+ return click.Group.get_command(self, ctx, name)275 276 def list_commands(self, ctx):277 # The commands available is the list of both the application (if278 # available) plus the builtin commands.228- rv = set(super(ContextGroupMixin, self).list_commands(ctx))229- info = ctx.find_object(ScriptInfo)279+ rv = set(click.Group.list_commands(self, ctx))280+ info = ctx.ensure_object(ScriptInfo)281 try:282 rv.update(info.load_app().cli.list_commands(ctx))283 except NoAppException:284 pass3 unmodified lines288 with_context = cmd.callback is None or \289 not getattr(cmd.callback, '__flask_without_appcontext__', False)290 291 with ctx.find_object(ScriptInfo).conditional_context(with_context):241- return super(ContextGroupMixin, self).invoke_subcommand(242- ctx, cmd, cmd_name, args)292+ return click.Group.invoke_subcommand(293+ self, ctx, cmd, cmd_name, args)294 295+ def main(self, *args, **kwargs):296+ obj = kwargs.get('obj')297+ if obj is None:298+ obj = ScriptInfo(create_app=self.create_app)299+ kwargs['obj'] = obj300+ kwargs.setdefault('auto_envvar_prefix', 'FLASK')301+ return click.Group.main(self, *args, **kwargs)302 245-class FlaskGroup(ContextGroupMixin, click.Group):246- """Special subclass of the a regular click group that supports247- loading more commands from the configured Flask app.248- """303 250- def __init__(self, help=None):251- def set_app_id(ctx, value):252- if value is not None:253- if os.path.isfile(value):254- value = prepare_exec_for_file(value)255- elif '.' not in sys.path:256- sys.path.insert(0, '.')257- ctx.ensure_object(ScriptInfo).app_import_path = value258- def set_debug(ctx, value):259- ctx.ensure_object(ScriptInfo).debug = value260-261- click.Group.__init__(self, help=help, params=[262- click.Option(['-a', '--app'],263- help='The application to run',264- callback=set_app_id, is_eager=True),265- click.Option(['--debug/--no-debug'],266- help='Enable or disable debug mode.',267- default=None, callback=set_debug)268- ])269-270-271-cli = FlaskGroup(help='''\272-This shell command acts as general utility script for Flask applications.273-274-It loads the application configured (either through the FLASK_APP environment275-variable or the --app parameter) and then provides commands either provided276-by the application or Flask itself.277-278-The most useful commands are the "run" and "shell" command.279-280-Example usage:281-282- flask --app=hello --debug run283-''')284-285-286-@cli.command('run', short_help='Runs a development server.')304+@click.command('run', short_help='Runs a development server.')305 @click.option('--host', '-h', default='127.0.0.1',306 help='The interface to bind to.')307 @click.option('--port', '-p', default=5000,308 help='The port to bind to.')11 unmodified lines320 @without_appcontext321 @pass_script_info322 def run_command(info, host, port, reload, debugger, eager_loading,323 with_threads):306- """Runs a local development server for the Flask application."""324+ """Runs a local development server for the Flask application.325+326+ This local server is recommended for development purposes only but it327+ can also be used for simple intranet deployments. By default it will328+ not support any sort of concurrency at all to simplify debugging. This329+ can be changed with the --with-threads option which will enable basic330+ multithreading.331+332+ The reloader and debugger are by default enabled if the debug flag of333+ Flask is enabled and disabled otherwise.334+ """335 from werkzeug.serving import run_simple336 if reload is None:337 reload = info.debug338 if debugger is None:18 unmodified lines357 run_simple(host, port, app, use_reloader=reload,358 use_debugger=debugger, threaded=with_threads)359 360 333-@cli.command('shell', short_help='Runs a shell in the app context.')361+@click.command('shell', short_help='Runs a shell in the app context.')362 def shell_command():363 """Runs an interactive Python shell in the context of a given364 Flask application. The application will populate the default365 namespace of this shell according to it's configuration.21 unmodified lines387 """388 return click.Group()389 390 391+cli = FlaskGroup(help='''\392+This shell command acts as general utility script for Flask applications.393+394+It loads the application configured (either through the FLASK_APP environment395+variable or the --app parameter) and then provides commands either provided396+by the application or Flask itself.397+398+The most useful commands are the "run" and "shell" command.399+400+Example usage:401+402+ flask --app=hello --debug run403+''')404+405+406 def main(as_module=False):407 this_module = __package__ + '.cli'408 args = sys.argv[1:]409 9 unmodified lines419 sys.argv = ['-m', this_module] + sys.argv[1:]420 else:421 name = None422 380- cli.main(args=args, prog_name=name, obj=ScriptInfo(),381- auto_envvar_prefix='FLASK')423+ cli.main(args=args, prog_name=name)424 425 426 if __name__ == '__main__':427 main(as_module=True)