Merge pull request #2326 from HndrkMkt/#2264-handle-app-factory-in-FLASK_APP
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Handle app factory with arguments in FLASK_APP
authored by Kenneth Reitz · committed by GitHub · parents 63ddf2d, 48c2925 · Browse files · 3 files·+113 added−30 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+113 added−30 removed
- tests:+45 added−8 removed
- other:+68 added−22 removed
Provenance
- Commit
090109b- Tree
e2d7d07- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
63ddf2d- Parent 2
48c2925
3 files changed+113 added−30 removed
modified:flask/cli.py+68 added-22 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(2 unmodified lines81 'middleware.'.format(module=module.__name__)82 )83 84 82-def call_factory(func, script_info):83- """Checks if the given app factory function has an argument named 84- ``script_info`` or just a single argument and calls the function passing 85- ``script_info`` if so. Otherwise, calls the function without any arguments86- and returns the result.85+def call_factory(app_factory, script_info, arguments=()):86+ """Takes an app factory, a ``script_info` object and optionally a tuple87+ of arguments. Checks for the existence of a script_info argument and calls88+ the app_factory depending on that and the arguments provided.89 """88- arguments = getargspec(func).args89- if 'script_info' in arguments:90- return func(script_info=script_info)91- elif len(arguments) == 1:92- return func(script_info)93- return func()90+ arg_names = getargspec(app_factory).args91+ if 'script_info' in arg_names:92+ return app_factory(*arguments, script_info=script_info)93+ elif arguments:94+ return app_factory(*arguments)95+ elif not arguments and len(arg_names) == 1:96+ return app_factory(script_info)97+ return app_factory()98 99 100+def find_app_by_string(string, script_info, module):101+ """Checks if the given string is a variable name or a function. If it is 102+ a function, it checks for specified arguments and whether it takes 103+ a ``script_info`` argument and calls the function with the appropriate 104+ arguments. If it is a """105+ from . import Flask106+ function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'107+ match = re.match(function_regex, string)108+ if match:109+ name, args = match.groups()110+ try:111+ if args is not None:112+ args = args.rstrip(' ,')113+ if args:114+ args = ast.literal_eval(115+ "({args}, )".format(args=args))116+ else:117+ args = ()118+ app_factory = getattr(module, name, None)119+ app = call_factory(app_factory, script_info, args)120+ else:121+ attr = getattr(module, name, None)122+ if inspect.isfunction(attr):123+ app = call_factory(attr, script_info)124+ else:125+ app = attr126+127+ if isinstance(app, Flask):128+ return app129+ else:130+ raise RuntimeError('Failed to find application in module '131+ '"{name}"'.format(name=module))132+ except TypeError as e:133+ new_error = NoAppException(134+ '{e}\nThe app factory "{factory}" in module "{module}" could'135+ ' not be called with the specified arguments (and a'136+ ' script_info argument automatically added if applicable).'137+ ' Did you make sure to use the right number of arguments as'138+ ' well as not using keyword arguments or'139+ ' non-literals?'.format(e=e, factory=string, module=module))140+ reraise(NoAppException, new_error, sys.exc_info()[2])141+ else:142+ raise NoAppException(143+ 'The provided string "{string}" is not a valid variable name'144+ 'or function expression.'.format(string=string))145+146+147 def prepare_exec_for_file(filename):148 """Given a filename this will try to calculate the python path, add it149 to the search path and return the actual module name that is expected.150 """47 unmodified lines198 'ensure the extension is .py' % module)199 200 mod = sys.modules[module]201 if app_obj is None:151- app = find_best_app(script_info, mod)202+ return find_best_app(script_info, mod)203 else:153- app = getattr(mod, app_obj, None)154- if app is None:155- raise RuntimeError('Failed to find application in module "%s"'156- % module)204+ return find_app_by_string(app_obj, script_info, mod)205 158- return app206 160-207 def find_default_import_path():208 app = os.environ.get('FLASK_APP')209 if app is None:210 return457 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+30 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_app2('foo', 'bar', )"165+ ).name == "create_app2_foo_bar"166+ assert locate_app(167+ script_info, "cliapp.factory:create_app3('baz', 'qux')"168+ ).name == "create_app3_baz_qux"169 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")170+ pytest.raises(171+ NoAppException, locate_app, script_info, "notanpp.py")172+ pytest.raises(173+ NoAppException, locate_app, script_info, "cliapp/app")174+ pytest.raises(175+ RuntimeError, locate_app, script_info, "cliapp.app:notanapp")176+ pytest.raises(177+ NoAppException, locate_app,178+ script_info, "cliapp.factory:create_app2('foo')")179+ pytest.raises(180+ NoAppException, locate_app,181+ script_info, "cliapp.factory:create_app ()")182+ pytest.raises(183+ NoAppException, locate_app, script_info, "cliapp.importerrorapp")184 185 186 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):187 """Test of find_default_import_path."""181 unmodified lines