Preparation of a web frame in real python tutorial in the teacher Liaoxue Feng, see ( https://www.liaoxuefeng.com/wiki/1016959663602400/1018490695712544 ), which has a function add_routes, code is as follows:
def add_routes(app, module_name): n = module_name.rfind('.') if n == (-1): mod = __import__(module_name, globals(), locals()) else: name = module_name[n+1:] mod = getattr(__import__(module_name[:n], globals(), locals(), [name]), name) for attr in dir(mod): if attr.startswith('_'): continue fn = getattr(mod, attr) if callable(fn): method = getattr(fn, '__method__', None) path = getattr(fn, '__route__', None) if method and path: add_route(app, fn)
On the basis of Liao Xuefeng teacher code, I made some changes.
Import_module using a relatively simple way to view dynamic import function (control) packet, and then using a recursive method to all the modules walk_packages dynamic introduced into the package.
import importlib import pkgutil base = importlib.import_module('app.controller') for loader, module_name, is_pkg in pkgutil.walk_packages(base.__path__, f'{base.__name__}.'): try: sub_module = __import__(module_name, fromlist=['get_submodule']) except ImportError as e: raise e
# 后面代码略