Added click support to Flask
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 0ac492a · Browse files · 4 files·+392 added−251 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+392 added−251 removed
- other:+392 added−251 removed
Provenance
- Commit
3bdb90f- Tree
def0602- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0ac492a
4 files changed+392 added−251 removed
modified:flask/__main__.py+1 added-1 removed
9 unmodified lines10 """11 12 13 if __name__ == '__main__':14- from run import main14+ from cli import main15 main(as_module=True)modified:flask/app.py+44 added-3 removed
32 unmodified lines33 from .templating import DispatchingJinjaLoader, Environment, \34 _default_template_ctx_processor35 from .signals import request_started, request_finished, got_request_exception, \36 request_tearing_down, appcontext_tearing_down37+from .cli import make_default_cli38 from ._compat import reraise, string_types, text_type, integer_types39 40 # a lock used for logger initialization41 _logger_lock = Lock()434 unmodified lines476 self.template_context_processors = {477 None: [_default_template_ctx_processor]478 }479 480+ #: A list of shell context processor functions that should be run481+ #: when a shell context is created.482+ #:483+ #: .. versionadded:: 1.0484+ self.shell_context_processors = []485+486 #: all the attached blueprints in a dictionary by name. Blueprints487 #: can be attached multiple times so this dictionary does not tell488 #: you how often they got attached.489 #:47 unmodified lines537 self.add_url_rule(self.static_url_path + '/<path:filename>',538 endpoint='static',539 view_func=self.send_static_file)540 541+ #: The click command line context for this application. Commands542+ #: registered here show up in the ``flask`` command once the543+ #: application has been discovered. The default commands are544+ #: provided by Flask itself and can be overridden.545+ #:546+ #: This is an instance of a :class:`click.Group` object.547+ self.cli = make_default_cli(self)548+549 def _get_error_handlers(self):550 from warnings import warn551 warn(DeprecationWarning('error_handlers is deprecated, use the '552 'new error_handler_spec attribute instead.'), stacklevel=1)209 unmodified lines762 # easier add new variables in context processors without breaking763 # existing views.764 context.update(orig_ctx)765 766+ def make_shell_context(self):767+ """Returns the shell context for an interactive shell for this768+ application. This runs all the registered shell context769+ processors.770+771+ .. versionadded:: 1.0772+ """773+ rv = {'app': self, 'g': g}774+ for processor in self.shell_context_processors:775+ rv.update(processor())776+ return rv777+778 def run(self, host=None, port=None, debug=None, **options):779 """Runs the application on a local development server. If the780 :attr:`debug` flag is set the server will automatically reload781 for code changes and show a debugger in case an exception happened.2 unmodified lines784 code execution on the interactive debugger, you can pass785 ``use_evalex=False`` as parameter. This will keep the debugger's786 traceback screen active, but disable code execution.787 788+ It is not recommended to use this function for development with789+ automatic reloading as this is badly supported. Instead you should790+ be using the ``flask`` command line script's ``runserver``791+ support.792+793 .. admonition:: Keep in Mind794 795 Flask will suppress any server error with a generic error page796 unless it is in debug mode. As such to enable just the325 unmodified lines1122 .. versionadded:: 0.71123 Use :meth:`register_error_handler` instead of modifying1124 :attr:`error_handler_spec` directly, for application wide error1125 handlers.1094- 1126+1127 .. versionadded:: 0.71128 One can now additionally also register custom exception types1129 that do not necessarily have to be a subclass of the1130 :class:`~werkzeug.exceptions.HTTPException` class.226 unmodified lines1357 self.template_context_processors[None].append(f)1358 return f1359 1360 @setupmethod1361+ def shell_context_processor(self, f):1362+ """Registers a shell context processor function.1363+1364+ .. versionadded:: 1.01365+ """1366+ self.shell_context_processors.append(f)1367+ return f1368+1369+ @setupmethod1370 def url_value_preprocessor(self, f):1371 """Registers a function as URL value preprocessor for all view1372 functions of the application. It's called before the view functions1373 are called and can modify the url values provided.275 unmodified lines1649 # set the headers and status. We do this because there can be1650 # some extra logic involved when creating these objects with1651 # specific values (like default content type selection).1652 if isinstance(rv, (text_type, bytes, bytearray)):1612- rv = self.response_class(rv, headers=headers, status=status_or_headers)1653+ rv = self.response_class(rv, headers=headers,1654+ status=status_or_headers)1655 headers = status_or_headers = None1656 else:1657 rv = self.response_class.force_type(rv, request.environ)1658 6 unmodified lines1665 rv.headers.extend(headers)1666 1667 return rv1668 1627-1669 def create_url_adapter(self, request):1670 """Creates a URL adapter for the given request. The URL adapter1671 is created at a point where the request context is not yet set up1672 so the request is passed explicitly.250 unmodified linesadded:flask/cli.py+347 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.run4+ ~~~~~~~~~5+6+ A simple command line application to run flask apps.7+8+ :copyright: (c) 2014 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import sys14+from threading import Lock15+from contextlib import contextmanager16+17+import click18+19+from ._compat import iteritems20+21+22+class NoAppException(click.UsageError):23+ """Raised if an application cannot be found or loaded."""24+25+26+def find_best_app(module):27+ """Given a module instance this tries to find the best possible28+ application in the module or raises an exception.29+ """30+ from . import Flask31+32+ # Search for the most common names first.33+ for attr_name in 'app', 'application':34+ app = getattr(module, attr_name, None)35+ if app is not None and isinstance(app, Flask):36+ return app37+38+ # Otherwise find the only object that is a Flask instance.39+ matches = [v for k, v in iteritems(module.__dict__)40+ if isinstance(v, Flask)]41+42+ if matches:43+ if len(matches) > 1:44+ raise NoAppException('More than one possible Flask application '45+ 'found in module "%s", none of which are called '46+ '"app". Be explicit!' % module.__name__)47+ return matches[0]48+49+ raise NoAppException('Failed to find application in module "%s". Are '50+ 'you sure it contains a Flask application? Maybe '51+ 'you wrapped it in a WSGI middleware or you are '52+ 'using a factory function.' % module.__name__)53+54+55+def prepare_exec_for_file(filename):56+ module = []57+58+ # Chop off file extensions or package markers59+ if filename.endswith('.py'):60+ filename = filename[:-3]61+ elif os.path.split(filename)[1] == '__init__.py':62+ filename = os.path.dirname(filename)63+ filename = os.path.realpath(filename)64+65+ dirpath = filename66+ while 1:67+ dirpath, extra = os.path.split(dirpath)68+ module.append(extra)69+ if not os.path.isfile(os.path.join(dirpath, '__init__.py')):70+ break71+72+ sys.path.insert(0, dirpath)73+ return '.'.join(module[::-1])74+75+76+def locate_app(app_id, debug=None):77+ """Attempts to locate the application."""78+ if ':' in app_id:79+ module, app_obj = app_id.split(':', 1)80+ else:81+ module = app_id82+ app_obj = None83+84+ __import__(module)85+ mod = sys.modules[module]86+ if app_obj is None:87+ app = find_best_app(mod)88+ else:89+ app = getattr(mod, app_obj, None)90+ if app is None:91+ raise RuntimeError('Failed to find application in module "%s"'92+ % module)93+ if debug is not None:94+ app.debug = debug95+ return app96+97+98+class DispatchingApp(object):99+ """Special applicationt that dispatches to a flask application which100+ is imported by name on first request. This is safer than importing101+ the application upfront because it means that we can forward all102+ errors for import problems into the browser as error.103+ """104+105+ def __init__(self, app_id, debug=None, use_eager_loading=False):106+ self.app_id = app_id107+ self.app = None108+ self.debug = debug109+ self._lock = Lock()110+ if use_eager_loading:111+ self._load_unlocked()112+113+ def _load_unlocked(self):114+ self.app = rv = locate_app(self.app_id, self.debug)115+ return rv116+117+ def __call__(self, environ, start_response):118+ if self.app is not None:119+ return self.app(environ, start_response)120+ with self._lock:121+ if self.app is not None:122+ rv = self.app123+ else:124+ rv = self._load_unlocked()125+ return rv(environ, start_response)126+127+128+class ScriptInfo(object):129+ """Help object to deal with Flask applications. This is usually not130+ necessary to interface with as it's used internally in the dispatching131+ to click.132+ """133+134+ def __init__(self):135+ self.app_import_path = None136+ self.debug = None137+ self._loaded_app = None138+139+ def get_app_import_path(self):140+ """Return the actual application import path or fails if it is141+ not yet set.142+ """143+ if self.app_import_path is not None:144+ return self.app_import_path145+ raise NoAppException('Could not locate application. '146+ 'You did not provide FLASK_APP or the '147+ '--app parameter.')148+149+ def load_app(self):150+ """Loads the app (if not yet loaded) and returns it."""151+ if self._loaded_app is not None:152+ return self._loaded_app153+ rv = locate_app(self.get_app_import_path(), self.debug)154+ self._loaded_app = rv155+ return rv156+157+ @contextmanager158+ def conditional_context(self, with_context=True):159+ """Creates an application context or not, depending on the160+ given parameter but always works as context manager.161+ """162+ if with_context:163+ with self.load_app().app_context() as ctx:164+ yield ctx165+ else:166+ yield None167+168+169+pass_script_info = click.make_pass_decorator(ScriptInfo)170+171+172+def without_appcontext(f):173+ """Marks a click callback so that it does not get a app context174+ created. This only works for commands directly registered to175+ the toplevel system. This really is only useful for very176+ special commands like the runserver one.177+ """178+ f.__flask_without_appcontext__ = True179+ return f180+181+182+class FlaskClickGroup(click.Group):183+ """Special subclass of the a regular click group that supports184+ loading more commands from the configured Flask app.185+ """186+187+ def __init__(self, help=None):188+ def set_app_id(ctx, value):189+ if value is not None:190+ if os.path.isfile(value) or os.sep in value or \191+ os.altsep is not None and os.altsep in value:192+ value = prepare_exec_for_file(value)193+ ctx.obj.app_import_path = value194+ def set_debug(ctx, value):195+ ctx.obj.debug = value196+197+ click.Group.__init__(self, help=help, params=[198+ click.Option(['-a', '--app'],199+ help='The application to run',200+ callback=set_app_id, is_eager=True),201+ click.Option(['--debug/--no-debug'],202+ help='Enable or disable debug mode.',203+ default=None, callback=set_debug)204+ ])205+206+ def get_command(self, ctx, name):207+ info = ctx.find_object(ScriptInfo)208+ # Find the command in the application first, if we can find it.209+ # If the app is not available, we just ignore this silently.210+ try:211+ rv = info.load_app().cli.get_command(ctx, name)212+ if rv is not None:213+ return rv214+ except NoAppException:215+ pass216+ return click.Group.get_command(self, ctx, name)217+218+ def list_commands(self, ctx):219+ # The commands available is the list of both the application (if220+ # available) plus the builtin commands.221+ rv = set(click.Group.list_commands(self, ctx))222+ info = ctx.find_object(ScriptInfo)223+ try:224+ rv.update(info.load_app().cli.list_commands(ctx))225+ except NoAppException:226+ pass227+ return sorted(rv)228+229+ def invoke_subcommand(self, ctx, cmd, cmd_name, args):230+ with_context = cmd.callback is None or \231+ not getattr(cmd.callback, '__flask_without_appcontext__', False)232+233+ with ctx.find_object(ScriptInfo).conditional_context(with_context):234+ return click.Group.invoke_subcommand(235+ self, ctx, cmd, cmd_name, args)236+237+238+cli = FlaskClickGroup(help='''\239+This shell command acts as general utility script for Flask applications.240+241+It loads the application configured (either through the FLASK_APP environment242+variable or the --app parameter) and then provides commands either provided243+by the application or Flask itself.244+245+The most useful commands are the "run" and "shell" command.246+247+Example usage:248+249+ flask --app=hello --debug run250+''')251+252+253+@cli.command('run', short_help='Runs a development server.')254+@click.option('--host', '-h', default='127.0.0.1',255+ help='The interface to bind to.')256+@click.option('--port', '-p', default=5000,257+ help='The port to bind to.')258+@click.option('--reload/--no-reload', default=None,259+ help='Enable or disable the reloader. By default the reloader '260+ 'is active is debug is enabled.')261+@click.option('--debugger/--no-debugger', default=None,262+ help='Enable or disable the debugger. By default the debugger '263+ 'is active if debug is enabled.')264+@click.option('--eager-loading/--lazy-loader', default=None,265+ help='Enable or disable eager loading. By default eager '266+ 'loading is enabled if the reloader is disabled.')267+@click.option('--with-threads/--without-threads', default=False,268+ help='Enable or disable multithreading.')269+@without_appcontext270+@pass_script_info271+def run_command(info, host, port, reload, debugger, eager_loading,272+ with_threads):273+ """Runs a local development server for the Flask application."""274+ from werkzeug.serving import run_simple275+ app_id = info.get_app_import_path()276+ if reload is None:277+ reload = info.debug278+ if debugger is None:279+ debugger = info.debug280+ if eager_loading is None:281+ eager_loading = not reload282+283+ # Extra startup messages. This depends a but on Werkzeug internals to284+ # not double execute when the reloader kicks in.285+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':286+ print(' * Serving Flask app "%s"' % app_id)287+ if info.debug is not None:288+ print(' * Forcing debug %s' % (info.debug and 'on' or 'off'))289+290+ app = DispatchingApp(app_id, info.debug, eager_loading)291+ run_simple(host, port, app, use_reloader=reload,292+ use_debugger=debugger, threaded=with_threads)293+294+295+@cli.command('shell', short_help='Runs a shell in the app context.')296+def shell_command():297+ """Runs an interactive Python shell in the context of a given298+ Flask application. The application will populate the default299+ namespace of this shell according to it's configuration.300+301+ This is useful for executing small snippets of management code302+ without having to manually configuring the application.303+ """304+ import code305+ from flask.globals import _app_ctx_stack306+ app = _app_ctx_stack.top.app307+ banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (308+ sys.version,309+ sys.platform,310+ app.import_name,311+ app.debug and ' [debug]' or '',312+ app.instance_path,313+ )314+ code.interact(banner=banner, local=app.make_shell_context())315+316+317+def make_default_cli(app):318+ """Creates the default click object for the app itself. Currently319+ there are no default commands registered because all builtin commands320+ are registered on the actual cmd object here.321+ """322+ return click.Group()323+324+325+def main(as_module=False):326+ this_module = __package__ + '.cli'327+ args = sys.argv[1:]328+329+ if as_module:330+ if sys.version_info >= (2, 7):331+ name = 'python -m ' + this_module.rsplit('.', 1)[0]332+ else:333+ name = 'python -m ' + this_module334+335+ # This module is always executed as "python -m flask.run" and as such336+ # we need to ensure that we restore the actual command line so that337+ # the reloader can properly operate.338+ sys.argv = ['-m', this_module] + sys.argv[1:]339+ else:340+ name = 'flask'341+342+ cli.main(args=args, prog_name=name, obj=ScriptInfo(),343+ auto_envvar_prefix='FLASK')344+345+346+if __name__ == '__main__':347+ main(as_module=True)deleted:flask/run.py-247 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.run4- ~~~~~~~~~5-6- A simple command line application to run flask apps.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import sys14-from threading import Lock15-from optparse import OptionParser16-17-from werkzeug.serving import run_simple18-19-from ._compat import iteritems20-21-22-def find_best_app(module):23- """Given a module instance this tries to find the best possible application24- in the module or raises a RuntimeError.25- """26- from flask import Flask27-28- # The app name wins, even if it's not a flask object.29- app = getattr(module, 'app', None)30- if app is not None and callable(app):31- return app32-33- # Otherwise find the first object named Flask34- matches = []35- for key, value in iteritems(module.__dict__):36- if isinstance(value, Flask):37- matches.append(value)38-39- if matches:40- if len(matches) > 1:41- raise RuntimeError('More than one possible Flask application '42- 'found in module "%s", none of which are called '43- '"app". Be explicit!' % module)44- return matches[0]45-46- raise RuntimeError('Failed to find application in module "%s". Are '47- 'you sure it contains a Flask application? Maybe '48- 'you wrapped it in a WSGI middleware or you are '49- 'using a factory function.' % module)50-51-52-def prepare_exec_for_file(filename):53- module = []54-55- # Chop off file extensions or package markers56- if filename.endswith('.py'):57- filename = filename[:-3]58- elif os.path.split(filename)[1] == '__init__.py':59- filename = os.path.dirname(filename)60- filename = os.path.realpath(filename)61-62- dirpath = filename63- while 1:64- dirpath, extra = os.path.split(dirpath)65- module.append(extra)66- if not os.path.isfile(os.path.join(dirpath, '__init__.py')):67- break68-69- sys.path.insert(0, dirpath)70- return '.'.join(module[::-1])71-72-73-def locate_app(app_id, debug=None):74- """Attempts to locate the application."""75- if ':' in app_id:76- module, app_obj = app_id.split(':', 1)77- else:78- module = app_id79- app_obj = None80-81- __import__(module)82- mod = sys.modules[module]83- if app_obj is None:84- app = find_best_app(mod)85- else:86- app = getattr(mod, app_obj, None)87- if app is None:88- raise RuntimeError('Failed to find application in module "%s"'89- % module)90- if debug is not None:91- app.debug = debug92- return app93-94-95-class DispatchingApp(object):96- """Special applicationt that dispatches to a flask application which97- is imported by name on first request. This is safer than importing98- the application upfront because it means that we can forward all99- errors for import problems into the browser as error.100- """101-102- def __init__(self, app_id, debug=None, use_eager_loading=False):103- self.app_id = app_id104- self.app = None105- self.debug = debug106- self._lock = Lock()107- if use_eager_loading:108- self._load_unlocked()109-110- def _load_unlocked(self):111- self.app = rv = locate_app(self.app_id, self.debug)112- return rv113-114- def __call__(self, environ, start_response):115- if self.app is not None:116- return self.app(environ, start_response)117- with self._lock:118- if self.app is not None:119- rv = self.app120- else:121- rv = self._load_unlocked()122- return rv(environ, start_response)123-124-125-def run_application(app_id, host='127.0.0.1', port=5000, debug=None,126- use_reloader=False, use_debugger=False,127- use_eager_loading=None, magic_app_id=True,128- **options):129- """Useful function to start a Werkzeug server for an application that130- is known by it's import name. By default the app ID can also be a131- full file name in which case Flask attempts to reconstruct the import132- name from it and do the right thing.133-134- :param app_id: the import name of the application module. If a colon135- is provided, everything afterwards is the application136- object name. In case the magic app id is enabled this137- can also be a filename.138- :param host: the host to bind to.139- :param port: the port to bind to.140- :param debug: if set to something other than None then the application's141- debug flag will be set to this.142- :param use_reloader: enables or disables the reloader.143- :param use_debugger: enables or disables the builtin debugger.144- :param use_eager_loading: enables or disables eager loading. This is145- normally conditional to the reloader.146- :param magic_app_id: if this is enabled then the app id can also be a147- filename instead of an import module and Flask148- will attempt to reconstruct the import name.149- :param options: the options to be forwarded to the underlying150- Werkzeug server. See151- :func:`werkzeug.serving.run_simple` for more152- information.153- """154- if magic_app_id:155- if os.path.isfile(app_id) or os.sep in app_id or \156- os.altsep is not None and os.altsep in app_id:157- app_id = prepare_exec_for_file(app_id)158-159- if use_eager_loading is None:160- use_eager_loading = not use_reloader161-162- # Extra startup messages. This depends a but on Werkzeug internals to163- # not double execute when the reloader kicks in.164- if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':165- print ' * Serving Flask app "%s"' % app_id166- if debug is not None:167- print ' * Forcing debug %s' % (debug and 'on' or 'off')168-169- app = DispatchingApp(app_id, debug, use_eager_loading)170- run_simple(host, port, app, use_reloader=use_reloader,171- use_debugger=use_debugger, **options)172-173-174-def main(as_module=False):175- this_module = __package__ + '.run'176-177- if as_module:178- if sys.version_info >= (2, 7):179- name = 'python -m ' + this_module.rsplit('.', 1)[0]180- else:181- name = 'python -m ' + this_module182- else:183- name = 'flask-run'184-185- parser = OptionParser(usage='%prog [options] module', prog=name)186- parser.add_option('--debug', action='store_true',187- dest='debug', help='Flip debug flag on. If enabled '188- 'this also affects debugger and reloader defaults.')189- parser.add_option('--no-debug', action='store_false',190- dest='debug', help='Flip debug flag off.')191- parser.add_option('--host', default='127.0.0.1',192- help='The host to bind on. (defaults to 127.0.0.1)')193- parser.add_option('--port', default=5000,194- help='The port to bind on. (defaults to 5000)')195- parser.add_option('--with-reloader', action='store_true',196- dest='with_reloader',197- help='Enable the reloader.')198- parser.add_option('--without-reloader', action='store_false',199- dest='with_reloader',200- help='Disable the reloader.')201- parser.add_option('--with-debugger', action='store_true',202- dest='with_debugger',203- help='Enable the debugger.')204- parser.add_option('--without-debugger', action='store_false',205- dest='with_debugger',206- help='Disable the debugger.')207- parser.add_option('--with-eager-loading', action='store_true',208- dest='with_eager_loading',209- help='Force enable the eager-loading. This makes the '210- 'application load immediately but makes development '211- 'flows harder. It\'s not recommended to enable eager '212- 'loading when the reloader is enabled as it can lead '213- 'to unexpected crashes.')214- parser.add_option('--without-eager-loading', action='store_false',215- dest='with_eager_loading',216- help='Disable the eager-loading.')217- parser.add_option('--with-threads', action='store_true',218- dest='with_threads',219- help='Enable multi-threading to handle multiple '220- 'requests concurrently.')221- parser.add_option('--without-threads', action='store_false',222- dest='with_threads',223- help='Disables multi-threading. (default)')224- opts, args = parser.parse_args()225- if len(args) != 1:226- parser.error('Expected exactly one argument which is the import '227- 'name of the application.')228-229- if opts.with_debugger is None:230- opts.with_debugger = opts.debug231- if opts.with_reloader is None:232- opts.with_reloader = opts.debug233-234- # This module is always executed as "python -m flask.run" and as such235- # we need to ensure that we restore the actual command line so that236- # the reloader can properly operate.237- sys.argv = ['-m', this_module] + sys.argv[1:]238-239- run_application(args[0], opts.host, opts.port, debug=opts.debug,240- use_reloader=opts.with_reloader,241- use_debugger=opts.with_debugger,242- use_eager_loading=opts.with_eager_loading,243- threaded=opts.with_threads)244-245-246-if __name__ == '__main__':247- main(as_module=True)