Merge pull request #3564 from pallets/cli-ast-parse
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use ast to parse FLASK_APP
authored by David Lord · committed by GitHub · parents 0d04b40, ff2f713 · Browse files · 4 files·+67 added−40 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+67 added−40 removed
- tests:+0 added−1 removed
- other:+67 added−39 removed
Provenance
- Commit
2062d98- Tree
116f27f- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0d04b40- Parent 2
ff2f713
4 files changed+67 added−40 removed
modified:docs/cli.rst+2 added-2 removed
74 unmodified lines75 found, the command looks for a factory function named ``create_app`` or76 ``make_app`` that returns an instance.77 78 If parentheses follow the factory name, their contents are parsed as79-Python literals and passed as arguments to the function. This means that80-strings must still be in quotes.79+Python literals and passed as arguments and keyword arguments to the80+function. This means that strings must still be in quotes.81 82 83 Run the Development Server84 --------------------------453 unmodified linesmodified:src/flask/cli.py+63 added-37 removed
84 unmodified lines85 " to specify one."86 )87 88 89-def call_factory(script_info, app_factory, arguments=()):89+def call_factory(script_info, app_factory, args=None, kwargs=None):90 """Takes an app factory, a ``script_info` object and optionally a tuple91 of arguments. Checks for the existence of a script_info argument and calls92 the app_factory depending on that and the arguments provided.93 """94- args_spec = inspect.getfullargspec(app_factory)94+ sig = inspect.signature(app_factory)95+ args = [] if args is None else args96+ kwargs = {} if kwargs is None else kwargs97 96- if "script_info" in args_spec.args:98+ if "script_info" in sig.parameters:99 warnings.warn(100 "The 'script_info' argument is deprecated and will not be"101 " passed to the app factory function in 2.1.",102 DeprecationWarning,103 )102- return app_factory(*arguments, script_info=script_info)103- elif arguments:104- return app_factory(*arguments)105- elif not arguments and len(args_spec.args) == 1 and args_spec.defaults is None:104+ kwargs["script_info"] = script_info105+106+ if (107+ not args108+ and len(sig.parameters) == 1109+ and next(iter(sig.parameters.values())).default is inspect.Parameter.empty110+ ):111 warnings.warn(112 "Script info is deprecated and will not be passed as the"108- " first argument to the app factory function in 2.1.",113+ " single argument to the app factory function in 2.1.",114 DeprecationWarning,115 )111- return app_factory(script_info)116+ args.append(script_info)117 113- return app_factory()118+ return app_factory(*args, **kwargs)119 120 116-def _called_with_wrong_args(factory):121+def _called_with_wrong_args(f):122 """Check whether calling a function raised a ``TypeError`` because123 the call failed or because something in the factory raised the124 error.125 121- :param factory: the factory function that was called122- :return: true if the call failed126+ :param f: The function that was called.127+ :return: ``True`` if the call failed.128 """129 tb = sys.exc_info()[2]130 131 try:132 while tb is not None:128- if tb.tb_frame.f_code is factory.__code__:129- # in the factory, it was called successfully133+ if tb.tb_frame.f_code is f.__code__:134+ # In the function, it was called successfully.135 return False136 137 tb = tb.tb_next138 134- # didn't reach the factory139+ # Didn't reach the function.140 return True141 finally:137- # explicitly delete tb as it is circular referenced142+ # Delete tb to break a circular reference.143 # https://docs.python.org/2/library/sys.html#sys.exc_info144 del tb145 146 2 unmodified lines149 a function to get the app instance, or return the variable directly.150 """151 from . import Flask152 148- match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)149-150- if not match:153+ # Parse app_name as a single expression to determine if it's a valid154+ # attribute name or function call.155+ try:156+ expr = ast.parse(app_name.strip(), mode="eval").body157+ except SyntaxError:158 raise NoAppException(152- f"{app_name!r} is not a valid variable name or function expression."159+ f"Failed to parse {app_name!r} as an attribute name or function call."160 )161 155- name, args = match.groups()162+ if isinstance(expr, ast.Name):163+ name = expr.id164+ args = kwargs = None165+ elif isinstance(expr, ast.Call):166+ # Ensure the function name is an attribute name only.167+ if not isinstance(expr.func, ast.Name):168+ raise NoAppException(169+ f"Function reference must be a simple name: {app_name!r}."170+ )171 172+ name = expr.func.id173+174+ # Parse the positional and keyword arguments as literals.175+ try:176+ args = [ast.literal_eval(arg) for arg in expr.args]177+ kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}178+ except ValueError:179+ # literal_eval gives cryptic error messages, show a generic180+ # message with the full expression instead.181+ raise NoAppException(182+ f"Failed to parse arguments as literal values: {app_name!r}."183+ )184+ else:185+ raise NoAppException(186+ f"Failed to parse {app_name!r} as an attribute name or function call."187+ )188+189 try:190 attr = getattr(module, name)159- except AttributeError as e:160- raise NoAppException(e.args[0])191+ except AttributeError:192+ raise NoAppException(193+ f"Failed to find attribute {name!r} in {module.__name__!r}."194+ )195 196+ # If the attribute is a function, call it with any args and kwargs197+ # to get the real application.198 if inspect.isfunction(attr):163- if args:164- try:165- args = ast.literal_eval(f"({args},)")166- except (ValueError, SyntaxError):167- raise NoAppException(f"Could not parse the arguments in {app_name!r}.")168- else:169- args = ()170-199 try:172- app = call_factory(script_info, attr, args)173- except TypeError as e:200+ app = call_factory(script_info, attr, args, kwargs)201+ except TypeError:202 if not _called_with_wrong_args(attr):203 raise204 205 raise NoAppException(178- f"{e}\nThe factory {app_name!r} in module"206+ f"The factory {app_name!r} in module"207 f" {module.__name__!r} could not be called with the"208 " specified arguments."209 )210 else:178 unmodified lines389 390 if self._loaded_app is not None:391 return self._loaded_app392 365- app = None366-393 if self.create_app is not None:394 app = call_factory(self, self.create_app)395 else:396 if self.app_import_path:575 unmodified linesmodified:tests/test_cli.py-1 removed
201 unmodified lines202 ("cliapp.app", "testapp", "testapp"),203 ("cliapp.factory", None, "app"),204 ("cliapp.factory", "create_app", "app"),205 ("cliapp.factory", "create_app()", "app"),206- # no script_info206 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),207 # trailing comma space208 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),209 # strip whitespace447 unmodified linesmodified:CHANGES.rst+2 added
23 unmodified lines24 :mod:`io` object in text mode. Previously, it would respond with25 200 OK and an empty file. :issue:`3358`26 - When using ad-hoc certificates, check for the cryptography library27 instead of PyOpenSSL. :pr:`3492`28+- When specifying a factory function with ``FLASK_APP``, keyword29+ argument can be passed. :issue:`3553`30 31 32 Version 1.1.233 -------------1011 unmodified lines