def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name pattern.""" warnings.warn('find_related_modules has been deprecated.', DeprecationWarning) package_elements = package.rsplit(".", 1) try: if len(package_elements) == 2: pkg = __import__(package_elements[0], globals(), locals(), [ package_elements[1]]) pkg = getattr(pkg, package_elements[1]) else: pkg = __import__(package_elements[0], globals(), locals(), []) pkg_path = pkg.__path__ except AttributeError: return [] # Find all modules named according to related_name p = re.compile(related_name_re) modules = [] for name in find_modules(package, include_packages=True): if p.match(name.split('.')[-1]): try: modules.append(import_string(name, silent=ignore_exceptions)) except Exception as e: if not ignore_exceptions: raise e return modules
def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Given a package name and a module name pattern, tries to find matching modules.""" package_elements = package.rsplit(".", 1) try: if len(package_elements) == 2: pkg = __import__(package_elements[0], globals(), locals(), [package_elements[1]]) pkg = getattr(pkg, package_elements[1]) else: pkg = __import__(package_elements[0], globals(), locals(), []) pkg_path = pkg.__path__ except AttributeError: return [] # Find all modules named according to related_name p = re.compile(related_name_re) modules = [] for name in find_modules(package, include_packages=True): if p.match(name.split('.')[-1]): try: modules.append(import_string(name, silent=ignore_exceptions)) except Exception as e: if not ignore_exceptions: raise e return modules
def run_tests(): """Run all doctests.""" from werkzeug import find_modules modules = find_modules("apollo", include_packages=True, recursive=True) tests = unittest.TestSuite() for module in modules: tests.addTests(doctest.DocTestSuite(module)) return tests
def register_blueprints(app: flask.Flask) -> None: # Every sub-view needs to be imported to populate the blueprint. # If this is not done, we will have empty blueprints. # If we register every module with the ``bp`` attribute normally, # we would have a lot of duplicate routes, which Werkzeug doesn't filter. for name in find_modules('core', recursive=True): if not name.endswith('conftest'): import_string(name) # Now import and register each blueprint. Since each blueprint # is defined in the package's __init__, we scan packages this time, # unlike the last. for name in find_modules('core', include_packages=True): if not name.endswith('conftest'): mod = import_string(name) if hasattr(mod, 'bp'): app.register_blueprint(mod.bp)
def find_models_and_tables(): models_dict = {} for module_name in find_modules('app', include_packages=True): models_module = import_string('%s.models' % module_name, silent=True) if models_module: for name, item in models_module.__dict__.items(): if (inspect.isclass(item) and Model in inspect.getmro(item)) \ or item.__class__ is Table: models_dict[name] = item return models_dict
def load_modules(self, package, name): modules = tuple(find_modules(package, include_packages=True)) fullname = '%s.%s' % (package, name) result = [] if fullname in modules: mod = import_string(fullname) result.append(mod) try: submodules = tuple(find_modules(fullname)) except (ValueError, AttributeError): return result for module in submodules: mod = import_string(module) result.append(mod) return result
def build_suite(name): """Build test suite for the given name. A name can be either a package name or a fully qualified name of the test class or a specific test method within a package prefixed with ``package_name:``. For example: >>> build_suite('hello') >>> build_suite('hello:HelloTest') >>> build_suite('hello:HelloTest.test_hello') >>> build_suite('foo:foo.FooTest') >>> build_suite('foo:bar.BarTest') :returns: an instance of `TestSuite` """ try: package, test = name.split(':') except: package, test = name, None test_module = '%s.%s' % (package, TEST_MODULE) test_fullname = '%s.%s' % (test_module, test) if test else test_module suite = unittest.TestSuite() match = re.match('(.*?)\.(test_\w+)$', test_fullname) if match: try: TestClass = import_string(match.group(1)) except ImportError: raise ImportError(match.group(1)) suite.addTest(TestClass(match.group(2))) elif test: try: TestClass = import_string(test_fullname) except AttributeError: raise AttributeError(test_fullname) if isinstance(TestClass, unittest.TestCase.__class__): suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestClass)) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(TestClass)) else: try: test_modules = list(find_modules(test_module)) except ValueError: test_modules = [test_module] for module in map(import_string, test_modules): suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(module)) return suite
def load_modules(self, package, name): """Load the module/submodules of the given package by given name. """ modules = tuple(find_modules(package, include_packages=True)) fullname = '%s.%s' % (package, name) result = [] if fullname in modules: logger.info(' * Loading module: %s' % fullname) mod = import_string(fullname) result.append(mod) try: submodules = tuple(find_modules(fullname)) except (ValueError, AttributeError): return result for module in submodules: logger.info(' * Loading module: %s' % module) mod = import_string(module) result.append(mod) return result
def init_app(self, app): ''' - load config from FLASK_APPS_CFG env var - run through installed_blueprints and import - import modules within blueprints ''' blueprints = [] app.extensions = app.extensions or {} app.extensions['apps'] = {} app.extensions['apps']['_has_models'] = False if 'FLASK_APPS_CFG' in os.environ: app.config.from_envvar('FLASK_APPS_CFG') if app.config.get('DATABASE_URI'): os.environ['DATABASE_URI'] = app.config.get('DATABASE_URI') if 'INSTALLED_BLUEPRINTS' in app.config: blueprints = app.config['INSTALLED_BLUEPRINTS'] bps = [] for b in blueprints: module = import_string(b) children = list(find_modules(b)) bp = getattr(module, b.rsplit('.', 1)[-1]) bps.append(bp) for child in children: if child.endswith('models'): app.extensions['apps']['_has_models'] = True import_string(child) if app.extensions['apps']['_has_models'] and app.config.get( 'DATABASE_URI'): app.extensions['apps']['_db_engine'] = create_engine( app.config['DATABASE_URI'], echo=True) else: app.extensions['apps']['_db_engine'] = None for bp in bps: if not bp.name in app.blueprints: try: app.register_blueprint(bp) except: pass
def _import_module(module, ignore_modules=None): """Import the components to setup the metaclass magic. :param module: A string defining either a package or a module. You can use star-magic to setup packages recursivly. :param ignore_modules: Modules to ignore if they are specified in `modules` """ ignore_modules = ignore_modules or [] # No star at the end means a package/module/class but nothing below. if module[-1] != "*": yield import_string(module) else: try: for mod in find_modules(module[:-2], True, True): if mod not in ignore_modules: yield import_string(mod) # find_modules does import our package, but doesn't yield it # hence we import it ourself. yield import_string(module[:-2]) except ValueError: # module is a module and not a package yield import_string(module[:-2])
def init_app(self,app): ''' - load config from FLASK_APPS_CFG env var - run through installed_blueprints and import - import modules within blueprints ''' blueprints = [] app.extensions = app.extensions or {} app.extensions['apps'] = {} app.extensions['apps']['_has_models'] = False if 'FLASK_APPS_CFG' in os.environ: app.config.from_envvar('FLASK_APPS_CFG') if app.config.get('DATABASE_URI'): os.environ['DATABASE_URI'] = app.config.get('DATABASE_URI') if 'INSTALLED_BLUEPRINTS' in app.config: blueprints = app.config['INSTALLED_BLUEPRINTS'] bps = [] for b in blueprints: module = import_string(b) children = list(find_modules(b)) bp = getattr(module,b.rsplit('.',1)[-1]) bps.append(bp) for child in children: if child.endswith('models'): app.extensions['apps']['_has_models'] = True import_string(child) if app.extensions['apps']['_has_models'] and app.config.get('DATABASE_URI'): app.extensions['apps']['_db_engine'] = create_engine(app.config['DATABASE_URI'],echo=True) else: app.extensions['apps']['_db_engine'] = None for bp in bps: if not bp.name in app.blueprints: try: app.register_blueprint(bp) except: pass
def _import_module(module, ignore_modules=None): """Import the components to setup the metaclass magic. :param module: A string defining either a package or a module. You can use star-magic to setup packages recursivly. :param ignore_modules: Modules to ignore if they are specified in `modules` """ ignore_modules = ignore_modules or [] # No star at the end means a package/module/class but nothing below. if module[-1] != '*': yield import_string(module) else: try: for mod in find_modules(module[:-2], True, True): if mod not in ignore_modules: yield import_string(mod) # find_modules does import our package, but doesn't yield it # hence we import it ourself. yield import_string(module[:-2]) except ValueError: # module is a module and not a package yield import_string(module[:-2])
def views_register(app): for name in find_modules('miniapp.views'): mod = import_string(name) if hasattr(mod, 'bp'): app.register_blueprint(mod.bp)
def __init__(self): self.prog = os.path.basename(sys.argv[0]) # load all the available commands for m in find_modules('kalapy.admin.commands'): import_string(m)
app.jinja_env.filters['date'] = helpers.format_date app.jinja_env.filters['time'] = helpers.format_time app.jinja_env.filters['datetime'] = helpers.format_datetime app.config.update(prod) if prod['DEBUG'] is True or prod['DEBUG'] is None: app.config.update(dev) app.debug = True db = Peewee(app) #toobar = DebugToolbarExtension(app) if db: import app.models as models app.cli.add_command(db.cli, 'db') for name in find_modules('app.blueprints'): mod = import_string(name) if hasattr(mod, 'blueprint'): app.register_blueprint(mod.blueprint) @app.before_request def before_request(): g.startTime = datetime.now() g.errors = session.pop("validationErrors", []) g.hasErrors = len(g.errors) > 0 g.data = session.pop("validationData", {}) g.loggedIn = False if "user" in session: try: g.User = models.User.select().where(
def init_app(app): with app.app_context(): for name in find_modules('wiki', recursive=True): import_string(name) app.register_blueprint(routes.bp)
def modules(self): return find_modules(self.module_folder, self.include_packages, self.recursive)