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)
| 118 | |
| 119 | |
| 120 | def 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: |
no test coverage detected