Skip to content
Myr

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

3 files+81 added−58 removed

modified:flask/cli.py+71 added-56 removed
44 unmodified lines
4546 # Search for the most common names first.47 for attr_name in ('app', 'application'):48 app = getattr(module, attr_name, None)4950 if isinstance(app, Flask):51 return app5253 # Otherwise find the only object that is a Flask instance.
4 unmodified lines
58 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 )6667 # Search for app factory functions.68 for attr_name in ('create_app', 'make_app'):69 app_factory = getattr(module, attr_name, None)7071 if inspect.isfunction(app_factory):72 try:72 app = call_factory(app_factory, script_info)73 app = call_factory(script_info, app_factory)7475 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 )8687 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 )939490def call_factory(app_factory, script_info, arguments=()):95def 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 lines
106 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)110111 return app_factory()112113108def 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 = attr114def 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)122135 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 )128129 name, args = match.groups()130131 try:132 attr = getattr(module, name)133 except AttributeError as e:134 raise NoAppException(e.args[0])135136 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 = ()147148 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 = attr159160 if isinstance(app, Flask):161 return app162163 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 )169170171def 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 lines
196 return '.'.join(module_name[::-1])197198199def locate_app(script_info, module_name, app_name, raise_if_not_found=True):184 """Attempts to locate the application."""200 __traceback_hide__ = True201202 try:203 __import__(module_name)
16 unmodified lines
220221 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)225226227def get_version(ctx, param, value):228 if not value or ctx.resilient_parsing:
97 unmodified lines
326327 app = None328329 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 lines
modified:tests/test_apps/cliapp/factory.py+4 added
11 unmodified lines
121314def create_app3(foo, script_info):15 return Flask('_'.join(['app3', foo, script_info.data['test']]))161718def no_app():19 pass
modified:tests/test_cli.py+6 added-2 removed
198 unmodified lines
199 # 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))206def test_locate_app(test_apps, iname, aname, result):207 info = ScriptInfo()208 info.data['test'] = 'spam'
5 unmodified lines
214 ('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))227def test_locate_app_raises(test_apps, iname, aname):228 info = ScriptInfo()229
248 unmodified lines