MCPcopy
hub / github.com/benoitc/gunicorn / import_app

Function import_app

gunicorn/util.py:403–483  ·  view source on GitHub ↗
(module)

Source from the content-addressed store, hash-verified

401
402
403def import_app(module):
404 parts = module.split(":", 1)
405 if len(parts) == 1:
406 obj = "application"
407 else:
408 module, obj = parts[0], parts[1]
409
410 try:
411 mod = importlib.import_module(module)
412 except ImportError:
413 if module.endswith(".py") and os.path.exists(module):
414 msg = "Failed to find application, did you mean '%s:%s'?"
415 raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
416 raise
417
418 # Parse obj as a single expression to determine if it's a valid
419 # attribute name or function call.
420 try:
421 expression = ast.parse(obj, mode="eval").body
422 except SyntaxError:
423 raise AppImportError(
424 "Failed to parse %r as an attribute name or function call." % obj
425 )
426
427 if isinstance(expression, ast.Name):
428 name = expression.id
429 args = kwargs = None
430 elif isinstance(expression, ast.Call):
431 # Ensure the function name is an attribute name only.
432 if not isinstance(expression.func, ast.Name):
433 raise AppImportError("Function reference must be a simple name: %r" % obj)
434
435 name = expression.func.id
436
437 # Parse the positional and keyword arguments as literals.
438 try:
439 args = [ast.literal_eval(arg) for arg in expression.args]
440 kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expression.keywords}
441 except ValueError:
442 # literal_eval gives cryptic error messages, show a generic
443 # message with the full expression instead.
444 raise AppImportError(
445 "Failed to parse arguments as literal values: %r" % obj
446 )
447 else:
448 raise AppImportError(
449 "Failed to parse %r as an attribute name or function call." % obj
450 )
451
452 is_debug = logging.root.level == logging.DEBUG
453 try:
454 app = getattr(mod, name)
455 except AttributeError:
456 if is_debug:
457 traceback.print_exception(*sys.exc_info())
458 raise AppImportError("Failed to find attribute %r in %r." % (name, module))
459
460 # If the expression was a function call, call the retrieved object

Callers

nothing calls this directly

Calls 5

AppImportErrorClass · 0.90
_called_with_wrong_argsFunction · 0.85
existsMethod · 0.80
appFunction · 0.70
parseMethod · 0.45

Tested by

no test coverage detected