|
- # Copyright P G Jones 2018.
- #
- # Permission is hereby granted, free of charge, to any person
- # obtaining a copy of this software and associated documentation
- # files (the "Software"), to deal in the Software without
- # restriction, including without limitation the rights to use,
- # copy, modify, merge, publish, distribute, sublicense, and/or sell
- # copies of the Software, and to permit persons to whom the
- # Software is furnished to do so, subject to the following
- # conditions:
- #
- # The above copyright notice and this permission notice shall be
- # included in all copies or substantial portions of the Software.
- #
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- # OTHER DEALINGS IN THE SOFTWARE.
- #
-
- # Obtained from:
- # https://github.com/pgjones/hypercorn/blob/master/src/hypercorn/utils.py
- #
- # Slightly modified to adapt to my uses.
- #
- # Remove import path from sys.path as part of clean up.
- #
- # Use getattr instead of eval.
-
- import sys
-
- from pathlib import Path
- from importlib import import_module
-
- def load_application(path: str):
- try:
- module_name, app_name = path.split(":", 1)
- except ValueError:
- module_name, app_name = path, "func"
- except AttributeError:
- raise ValueError()
-
- module_path = Path(module_name).resolve()
- added_module = str(module_path.parent)
- sys.path.insert(0, added_module)
- try:
- if module_path.is_file():
- import_name = module_path.with_suffix("").name
- else:
- import_name = module_path.name
- try:
- module = import_module(import_name)
- except ModuleNotFoundError as error:
- if error.name == import_name:
- raise ValueError('module %s not found' %
- repr(import_name))
- else:
- raise
-
- try:
- for i in app_name.split('.'):
- module = getattr(module, i)
- return module
- except AttributeError:
- raise ValueError('attribute %s not found on %s' %
- (repr(i), repr(module)))
- finally:
- sys.path.remove(added_module)
|