rewrite cli errors
Before adoption: this commit came in with the history the project adopted, so no landing records it.
consistent order for arguments to load functions refactor find_app_by_string to flow better more cli loader tests
authored by David Lord · committed by David Lord · parent 8020d5e · Browse files · 3 files·+81 added−58 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+81 added−58 removed
- tests:+10 added−2 removed
- other:+71 added−56 removed
Provenance
- Commit
5436ddd- Tree
a501876- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
8020d5e
3 files changed+81 added−58 removed
modified:flask/cli.py+71 added-56 removed
44 unmodified lines45 46 # Search for the most common names first.47 for attr_name in ('app', 'application'):48 app = getattr(module, attr_name, None)49+50 if isinstance(app, Flask):51 return app52 53 # Otherwise find the only object that is a Flask instance.4 unmodified lines58 if len(matches) == 1:59 return matches[0]60 elif len(matches) > 1:61 raise NoAppException(61- 'Auto-detected multiple Flask applications in module "{module}".'62- ' Use "FLASK_APP={module}:name" to specify the correct'63- ' one.'.format(module=module.__name__)62+ 'Detected multiple Flask applications in module "{module}". Use '63+ '"FLASK_APP={module}:name" to specify the correct '64+ 'one.'.format(module=module.__name__)65 )66 67 # Search for app factory functions.68 for attr_name in ('create_app', 'make_app'):69 app_factory = getattr(module, attr_name, None)70 71 if inspect.isfunction(app_factory):72 try:72- app = call_factory(app_factory, script_info)73+ app = call_factory(script_info, app_factory)74+75 if isinstance(app, Flask):76 return app77 except TypeError:78 raise NoAppException(77- 'Auto-detected "{function}()" in module "{module}", but '78- 'could not call it without specifying arguments.'.format(79- function=attr_name, module=module.__name__79+ 'Detected factory "{factory}" in module "{module}", but '80+ 'could not call it without arguments. Use '81+ '"FLASK_APP=\'{module}:{factory}(args)\'" to specify '82+ 'arguments.'.format(83+ factory=attr_name, module=module.__name__84 )85 )86 87 raise NoAppException(84- 'Failed to find application in module "{module}". Are you sure '85- 'it contains a Flask application? Maybe you wrapped it in a WSGI '86- 'middleware.'.format(module=module.__name__)88+ 'Failed to find Flask application or factory in module "{module}". '89+ 'Use "FLASK_APP={module}:name to specify one.'.format(90+ module=module.__name__91+ )92 )93 94 90-def call_factory(app_factory, script_info, arguments=()):95+def call_factory(script_info, app_factory, arguments=()):96 """Takes an app factory, a ``script_info` object and optionally a tuple97 of arguments. Checks for the existence of a script_info argument and calls98 the app_factory depending on that and the arguments provided.99 """6 unmodified lines106 elif arguments:107 return app_factory(*arguments)108 elif not arguments and len(arg_names) == 1 and arg_defaults is None:109 return app_factory(script_info)110+111 return app_factory()112 113 108-def find_app_by_string(string, script_info, module):109- """Checks if the given string is a variable name or a function. If it is110- a function, it checks for specified arguments and whether it takes111- a ``script_info`` argument and calls the function with the appropriate112- arguments."""113- from . import Flask114- function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'115- match = re.match(function_regex, string)116- if match:117- name, args = match.groups()118- try:119- if args is not None:120- args = args.rstrip(' ,')121- if args:122- args = ast.literal_eval(123- "({args}, )".format(args=args))124- else:125- args = ()126- app_factory = getattr(module, name, None)127- app = call_factory(app_factory, script_info, args)128- else:129- attr = getattr(module, name, None)130- if inspect.isfunction(attr):131- app = call_factory(attr, script_info)132- else:133- app = attr114+def find_app_by_string(script_info, module, app_name):115+ """Checks if the given string is a variable name or a function. If it is a116+ function, it checks for specified arguments and whether it takes a117+ ``script_info`` argument and calls the function with the appropriate118+ arguments.119+ """120+ from flask import Flask121+ match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name)122 135- if isinstance(app, Flask):136- return app137- else:138- raise NoAppException('Failed to find application in module '139- '"{name}"'.format(name=module))123+ if not match:124+ raise NoAppException(125+ '"{name}" is not a valid variable name or function '126+ 'expression.'.format(name=app_name)127+ )128+129+ name, args = match.groups()130+131+ try:132+ attr = getattr(module, name)133+ except AttributeError as e:134+ raise NoAppException(e.args[0])135+136+ if inspect.isfunction(attr):137+ if args:138+ try:139+ args = ast.literal_eval('({args},)'.format(args=args))140+ except (ValueError, SyntaxError)as e:141+ raise NoAppException(142+ 'Could not parse the arguments in '143+ '"{app_name}".'.format(e=e, app_name=app_name)144+ )145+ else:146+ args = ()147+148+ try:149+ app = call_factory(script_info, attr, args)150 except TypeError as e:141- new_error = NoAppException(142- '{e}\nThe app factory "{factory}" in module "{module}" could'143- ' not be called with the specified arguments (and a'144- ' script_info argument automatically added if applicable).'145- ' Did you make sure to use the right number of arguments as'146- ' well as not using keyword arguments or'147- ' non-literals?'.format(e=e, factory=string, module=module))148- reraise(NoAppException, new_error, sys.exc_info()[2])151+ raise NoAppException(152+ '{e}\nThe factory "{app_name}" in module "{module}" could not '153+ 'be called with the specified arguments.'.format(154+ e=e, app_name=app_name, module=module.__name__155+ )156+ )157 else:150- raise NoAppException(151- 'The provided string "{string}" is not a valid variable name'152- 'or function expression.'.format(string=string))158+ app = attr159 160+ if isinstance(app, Flask):161+ return app162 163+ raise NoAppException(164+ 'A valid Flask application was not obtained from '165+ '"{module}:{app_name}".'.format(166+ module=module.__name__, app_name=app_name167+ )168+ )169+170+171 def prepare_import(path):172 """Given a filename this will try to calculate the python path, add it173 to the search path and return the actual module name that is expected.174 """21 unmodified lines196 return '.'.join(module_name[::-1])197 198 199 def locate_app(script_info, module_name, app_name, raise_if_not_found=True):184- """Attempts to locate the application."""200 __traceback_hide__ = True201 202 try:203 __import__(module_name)16 unmodified lines220 221 if app_name is None:222 return find_best_app(script_info, module)223 else:209- return find_app_by_string(app_name, script_info, module)224+ return find_app_by_string(script_info, module, app_name)225 226 227 def get_version(ctx, param, value):228 if not value or ctx.resilient_parsing:97 unmodified lines326 327 app = None328 329 if self.create_app is not None:315- app = call_factory(self.create_app, self)330+ app = call_factory(self, self.create_app)331 else:332 if self.app_import_path:333 path, name = (self.app_import_path.split(':', 1) + [None])[:2]334 import_name = prepare_import(path)423 unmodified linesmodified:tests/test_apps/cliapp/factory.py+4 added
11 unmodified lines12 13 14 def create_app3(foo, script_info):15 return Flask('_'.join(['app3', foo, script_info.data['test']]))16+17+18+def no_app():19+ passmodified:tests/test_cli.py+6 added-2 removed
198 unmodified lines199 # trailing comma space200 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),201 # takes script_info202 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),203+ # strip whitespace204+ ('cliapp.factory', ' create_app () ', 'app'),205 ))206 def test_locate_app(test_apps, iname, aname, result):207 info = ScriptInfo()208 info.data['test'] = 'spam'5 unmodified lines214 ('cliapp/app', None),215 ('cliapp.app', 'notanapp'),216 # not enough arguments217 ('cliapp.factory', 'create_app2("foo")'),218+ # invalid identifier219+ ('cliapp.factory', 'create_app('),220+ # no app returned221+ ('cliapp.factory', 'no_app'),222 # nested import error223 ('cliapp.importerrorapp', None),224 # not a Python file225 ('cliapp.message.txt', None),220- # space before arg list221- ('cliapp.factory', 'create_app ()'),226 ))227 def test_locate_app_raises(test_apps, iname, aname):228 info = ScriptInfo()229 248 unmodified lines