Handle app factory with arguments in FLASK_APP
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Hendrik Makait · committed by Hendrik Makait · parent a4ae7f4 · Browse files · 3 files·+84 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+84 added−15 removed
- tests:+39 added−8 removed
- other:+45 added−7 removed
Provenance
- Commit
7106fb6- Tree
98d232d- Author
Hendrik Makait <hendrik.makait@googlemail.com>- Committer
Hendrik Makait <hendrik.makait@googlemail.com>- Parent
a4ae7f4
3 files changed+84 added−15 removed
modified:flask/cli.py+45 added-7 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import ast13+import inspect14 import os15+import re16 import sys17 import traceback18 from functools import update_wrapper19 from operator import attrgetter37 unmodified lines57 ' Use "FLASK_APP={module}:name" to specify the correct'58 ' one.'.format(module=module.__name__)59 )60 58- # Search for app factory callables.61+ # Search for app factory functions.62 for attr_name in ('create_app', 'make_app'):63 app_factory = getattr(module, attr_name, None)64 62- if callable(app_factory):65+ if inspect.isfunction(app_factory):66 try:67 app = call_factory(app_factory, script_info)68 if isinstance(app, Flask):69 return app70 except TypeError:71 raise NoAppException(69- 'Auto-detected "{callable}()" in module "{module}", but '72+ 'Auto-detected "{function}()" in module "{module}", but '73 'could not call it without specifying arguments.'.format(71- callable=attr_name, module=module.__name__74+ function=attr_name, module=module.__name__75 )76 )77 78 raise NoAppException(73 unmodified lines152 mod = sys.modules[module]153 if app_obj is None:154 app = find_best_app(script_info, mod)155 else:156+ function_regex = r'^([\w_][\w_\d]*)\((.*)\)$'157+ match = re.match(function_regex, app_obj)158+ try:159+ if match:160+ function_name = match.group(1)161+ arguments = match.group(2)162+ if arguments:163+ arguments = ast.literal_eval(164+ "({arguments}, )".format(arguments=arguments))165+ else:166+ arguments = ()167+ app_factory = getattr(mod, function_name, None)168+ app_factory_arg_names = getargspec(app_factory).args169+ if 'script_info' in app_factory_arg_names:170+ app = app_factory(*arguments, script_info=script_info)171+ elif arguments:172+ app = app_factory(*arguments)173+ elif not arguments and len(app_factory_arg_names) == 1:174+ app = app_factory(script_info)175+ else:176+ app = app_factory()177+ else:153- app = getattr(mod, app_obj, None)178+ attr = getattr(mod, app_obj, None)179+ if inspect.isfunction(attr):180+ app = call_factory(attr, script_info)181+ else:182+ app = attr183+ except TypeError as e:184+ new_error = NoAppException(185+ '{e}\nThe app factory "{factory}" in module "{module}" could'186+ ' not be called with the specified arguments (and a'187+ ' script_info argument automatically added if applicable).'188+ ' Did you make sure to use the right number of arguments as'189+ ' well as not using keyword arguments or'190+ ' non-literals?'.format(e=e, factory=app_obj, module=module))191+ reraise(NoAppException, new_error, sys.exc_info()[2])192 if app is None:155- raise RuntimeError('Failed to find application in module "%s"'156- % module)193+ raise RuntimeError('Failed to find application in module '194+ '"{name}"'.format(name=module))195 196 return app197 198 461 unmodified linesadded:tests/test_apps/cliapp/factory.py+15 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+6+def create_app():7+ return Flask('create_app')8+9+10+def create_app2(foo, bar):11+ return Flask("_".join(['create_app2', foo, bar]))12+13+14+def create_app3(foo, bar, script_info):15+ return Flask("_".join(['create_app3', foo, bar]))modified:tests/test_cli.py+24 added-8 removed
148 unmodified lines149 """Test of locate_app."""150 script_info = ScriptInfo()151 assert locate_app(script_info, "cliapp.app").name == "testapp"152 assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153+ assert locate_app(script_info, "cliapp.factory").name == "create_app"154+ assert locate_app(155+ script_info, "cliapp.factory").name == "create_app"156+ assert locate_app(157+ script_info, "cliapp.factory:create_app").name == "create_app"158+ assert locate_app(159+ script_info, "cliapp.factory:create_app()").name == "create_app"160+ assert locate_app(161+ script_info, "cliapp.factory:create_app2('foo', 'bar')"162+ ).name == "create_app2_foo_bar"163+ assert locate_app(164+ script_info, "cliapp.factory:create_app3('baz', 'qux')"165+ ).name == "create_app3_baz_qux"166 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"154- pytest.raises(NoAppException, locate_app,155- script_info, "notanpp.py")156- pytest.raises(NoAppException, locate_app,157- script_info, "cliapp/app")158- pytest.raises(RuntimeError, locate_app,159- script_info, "cliapp.app:notanapp")160- pytest.raises(NoAppException, locate_app,161- script_info, "cliapp.importerrorapp")167+ pytest.raises(168+ NoAppException, locate_app, script_info, "notanpp.py")169+ pytest.raises(170+ NoAppException, locate_app, script_info, "cliapp/app")171+ pytest.raises(172+ RuntimeError, locate_app, script_info, "cliapp.app:notanapp")173+ pytest.raises(174+ NoAppException, locate_app,175+ script_info, "cliapp.factory:create_app2('foo')")176+ pytest.raises(177+ NoAppException, locate_app, script_info, "cliapp.importerrorapp")178 179 180 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):181 """Test of find_default_import_path."""181 unmodified lines