Import model class in models package
320879
def import_model(cls, ins_name):
        
        try:
            package_space = getattr(cls, 'package_space')
        except AttributeError:
            raise ValueError('package_space not exist')
        else:
            return import_object(ins_name, package_space)
600838
def import_class(klass):
    ''''''
    mod = __import__(klass.rpartition('.')[0])
    for segment in klass.split('.')[1:-1]:
        mod = getattr(mod, segment)
    return getattr(mod, klass.rpartition('.')[2])
459647
def do_imports(self):
        
        self.do_import('worker_class', Worker)
        self.do_import('queue_model', self.options.worker_class.queue_model)
        self.do_import('error_model', self.options.worker_class.error_model)
        self.do_import('callback', self.options.worker_class.callback)
894109
def register_model(klass)
      LOCK.synchronize do
        models.push(klass) unless models.include?(klass)
      end
    end
1195356
def import_model(self, source):
        """"""
        source = self._resolve_source(source)
        self._context = FilePathContext(source)
        with self._context.open() as f:
            self._reader = self._open_reader(f)

        return self._reader.create_model()
964697
def import_model(self, source):
        """"""
        if not hasattr(source, 'read'):  # Not a File-like object
            with open(self._resolve_source(source), 'r') as f:
                return self._import(f)
        else:
            return self._import(source)
597485
def load_classes(package_str):
    ''''''

    _logger.debug('Loading all modules from %s', package_str)
    package = importlib.import_module(package_str)
    package_path = package.__path__
    _logger.debug('Searching for modules in package %s (%s)', package_str, package_path)
    for _, name, ispkg in pkgutil.iter_modules(package_path, package_str + "."):
        if not ispkg:
            _logger.debug('Found module: %s', name)
            module = importlib.import_module(name)
            if hasattr(module, CLASS_NAME_ATTR):
                class_name = getattr(module, CLASS_NAME_ATTR)
                _logger.debug('Found class: %s', class_name)
                clasz = getattr(module, class_name)

                if package_str not in _dynamo_cache:
                    _dynamo_cache[package_str] = CaseInsensitiveDict()
                
                if class_name not in _dynamo_cache[package_str]:
                    _dynamo_cache[package_str][class_name] = clasz
                    _logger.debug('Correctly loaded class: %s from: "%s"', class_name, package_str)
                else:
                    _logger.warning('Already loaded class: %s from: "%s"', class_name, package_str)
            else:
                _logger.warning('Module inside %s does not contain required attribute: %s', package_str, CLASS_NAME_ATTR)
        else:
            _logger.warning('Ignoring package: %s', name)

    if package_str in _dynamo_cache:
        return _dynamo_cache[package_str]
    else:
        return None
53550
def _load_model(self, dct):
        
        classname, version, _ = _pop_metadata(dct)

        _check_version(version)
        cls = self._models[classname]

        # Use `from_json` if available
        if hasattr(cls, 'from_json'):
            return cls.from_json(dct)

        # Default to object constructor
        return cls(**dct)
985394
def __model_class(self, model_name):
        
        build_schema = deepcopy(self.definitions[model_name])
        return self.schema_class(build_schema, model_name)
670029
def shell(filepath, wsgiapp, interpreter, models):
    
    model_base_classes = get_model_base_classes()
    imported_objects = {}

    if models and model_base_classes:
        insert_import_path_to_sys_modules(filepath)

        for module in find_modules_from_path(filepath):
            for name in dir(module):
                if name.startswith('_'):
                    continue
                obj = getattr(module, name)
                if isinstance(obj, model_base_classes):
                    key = name.split('.')[-1] if '.' in name else name
                    if key in imported_objects:
                        continue
                    imported_objects[key] = obj

    module = SourceFileLoader('module', filepath).load_module()
    imported_objects['app'] = getattr(module, wsgiapp)

    for key in imported_objects.keys():
        click.secho("import {}".format(key), fg='green')
    run_python(interpreter, imported_objects)
905995
def load_model(model_file):
    
    # Extract tar
    with tarfile.open(model_file) as tar:
        tarfolder = tempfile.mkdtemp()
        tar.extractall(path=tarfolder)

    from . import features
    from . import preprocessing

    # Get the preprocessing
    with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile:
        preprocessing_description = yaml.load(ymlfile)
    preprocessing_queue = preprocessing.get_preprocessing_queue(
        preprocessing_description['queue'])

    # Get the features
    with open(os.path.join(tarfolder, "features.yml"), 'r') as ymlfile:
        feature_description = yaml.load(ymlfile)
    feature_str_list = feature_description['features']
    feature_list = features.get_features(feature_str_list)

    # Get the model
    import nntoolkit.utils
    model = nntoolkit.utils.get_model(model_file)

    output_semantics_file = os.path.join(tarfolder, 'output_semantics.csv')
    output_semantics = nntoolkit.utils.get_outputs(output_semantics_file)

    # Cleanup
    shutil.rmtree(tarfolder)

    return (preprocessing_queue, feature_list, model, output_semantics)
690437
def copy_models(module_from, module_to):
    
    module_from = get_module(module_from)
    module_to = get_module(module_to)
    models = get_models(module_from)
    if models:
        models = models.copy()
        models.update(((t.key, t) for t in module_tables(module_from)))
        module_to.__odm_models__ = models
        return models
901882
def _lazy_load_get_model():
    
    if django is None:
        def _get_model(app, model):
            raise import_failure
    else:
        from django import apps as django_apps
        _get_model = django_apps.apps.get_model
    _LAZY_LOADS['get_model'] = _get_model
521059
def _initialize(self):
        
        meta = getattr(self, ModelBase._meta_attr)
        # read modelfile, convert JSON and load/update model
        if self.param_file is not None:
            self._load()
        LOGGER.debug('model:\n%r', self.model)
        # initialize layers
        # FIXME: move import inside loop for custom layers in different modules
        mod = importlib.import_module(meta.layers_mod, meta.layers_pkg)
        src_model = {}
        for layer, value in self.model.iteritems():
            # from layers module get the layer's class definition
            layer_cls = getattr(mod, meta.layer_cls_names[layer])  # class def
            self.layers[layer] = layer_cls  # add layer class def to model
            # check if model layers are classes
            src_value = {}  # layer value generated from source classes
            for src in value['sources']:
                # check if source has keyword arguments
                try:
                    src, kwargs = src
                except (TypeError, ValueError):
                    kwargs = {}  # no key work arguments
                # skip if not a source class
                if isinstance(src, basestring):
                    continue
                # generate layer value from source class
                src_value[src.__name__] = {'module': src.__module__,
                                           'package': None}
                # update layer keyword arguments
                src_value[src.__name__].update(kwargs)
            # use layer values generated from source class
            if src_value:
                value = src_model[layer] = src_value
            else:
                srcmod, srcpkg = value.get('module'), value.get('package')
                try:
                    value = dict(value['sources'])
                except ValueError:
                    value = dict.fromkeys(value['sources'], {})
                for src in value.viewkeys():
                    if srcmod is not None:
                        value[src]['module'] = srcmod
                    if srcpkg is not None:
                        value[src]['package'] = srcpkg
            # set layer attribute with model data
            setattr(self, layer, layer_cls(value))
        # update model with layer values generated from source classes
        if src_model:
            self.model.update(src_model)
        self._update()
        self._state = 'initialized'
878097
def load_raw(cls, model_fn, schema, *args, **kwargs):
        
        c = cls(*args, **kwargs)
        c.schema = schema.copy(schema_only=True)
        c._model_data = open(model_fn, 'rb').read()
        return c
123494
def resolve_model(self, model):
        '''
        
        '''
        if not model:
            raise ValueError('Unsupported model specifications')
        if isinstance(model, basestring):
            classname = model
        elif isinstance(model, dict) and 'class' in model:
            classname = model['class']
        else:
            raise ValueError('Unsupported model specifications')

        try:
            return get_document(classname)
        except self.NotRegistered:
            message = 'Model "{0}" does not exist'.format(classname)
            raise ValueError(message)
171562
def import_class_by_string(name):
    """"""
    components = name.split('.')
    clazz = components.pop()
    mod = __import__('.'.join(components))

    components += [clazz]
    for comp in components[1:]:
        mod = getattr(mod, comp)

    return mod