MCPcopy
hub / github.com/pallets/flask / find_app_by_string

Function find_app_by_string

src/flask/cli.py:120–197  ·  view source on GitHub ↗

Check if the given string is a variable name or a function. Call a function to get the app instance, or return the variable directly.

(module: ModuleType, app_name: str)

Source from the content-addressed store, hash-verified

118
119
120def find_app_by_string(module: ModuleType, app_name: str) -> Flask:
121 """Check if the given string is a variable name or a function. Call
122 a function to get the app instance, or return the variable directly.
123 """
124 from . import Flask
125
126 # Parse app_name as a single expression to determine if it's a valid
127 # attribute name or function call.
128 try:
129 expr = ast.parse(app_name.strip(), mode="eval").body
130 except SyntaxError:
131 raise NoAppException(
132 f"Failed to parse {app_name!r} as an attribute name or function call."
133 ) from None
134
135 if isinstance(expr, ast.Name):
136 name = expr.id
137 args = []
138 kwargs = {}
139 elif isinstance(expr, ast.Call):
140 # Ensure the function name is an attribute name only.
141 if not isinstance(expr.func, ast.Name):
142 raise NoAppException(
143 f"Function reference must be a simple name: {app_name!r}."
144 )
145
146 name = expr.func.id
147
148 # Parse the positional and keyword arguments as literals.
149 try:
150 args = [ast.literal_eval(arg) for arg in expr.args]
151 kwargs = {
152 kw.arg: ast.literal_eval(kw.value)
153 for kw in expr.keywords
154 if kw.arg is not None
155 }
156 except ValueError:
157 # literal_eval gives cryptic error messages, show a generic
158 # message with the full expression instead.
159 raise NoAppException(
160 f"Failed to parse arguments as literal values: {app_name!r}."
161 ) from None
162 else:
163 raise NoAppException(
164 f"Failed to parse {app_name!r} as an attribute name or function call."
165 )
166
167 try:
168 attr = getattr(module, name)
169 except AttributeError as e:
170 raise NoAppException(
171 f"Failed to find attribute {name!r} in {module.__name__!r}."
172 ) from e
173
174 # If the attribute is a function, call it with any args and kwargs
175 # to get the real application.
176 if inspect.isfunction(attr):
177 try:

Callers 1

locate_appFunction · 0.85

Calls 2

NoAppExceptionClass · 0.85
_called_with_wrong_argsFunction · 0.85

Tested by

no test coverage detected