Python源码示例:django.apps.apps.get_app_configs()

示例1
def discover_extensions(self):
        """Discover available extensions."""
        if self._discovery_done:
            return

        try:
            previous_state = self._extensions.copy()

            for app_config in apps.get_app_configs():
                indexes_path = "{}.extensions".format(app_config.name)
                try:
                    import_module(indexes_path)
                except ImportError:
                    pass

            self._discovery_done = True
        except Exception:
            # Rollback state to prevent corrupted state on exceptions during import.
            self._extensions = previous_state
            raise 
示例2
def get_apps_tools():
    """Get applications' tools and their paths.

    Return a dict with application names as keys and paths to tools'
    directories as values. Applications without tools are omitted.
    """
    tools_paths = {}

    for app_config in apps.get_app_configs():
        proc_path = os.path.join(app_config.path, "tools")
        if os.path.isdir(proc_path):
            tools_paths[app_config.name] = proc_path

    custom_tools_paths = getattr(settings, "RESOLWE_CUSTOM_TOOLS_PATHS", [])
    if not isinstance(custom_tools_paths, list):
        raise KeyError("`RESOLWE_CUSTOM_TOOLS_PATHS` setting must be a list.")

    for seq, custom_path in enumerate(custom_tools_paths):
        custom_key = "_custom_{}".format(seq)
        tools_paths[custom_key] = custom_path

    return tools_paths 
示例3
def discover_extensions(self):
        """Discover available extensions."""
        if self._discovery_done:
            return

        try:
            previous_state = self._extensions.copy()

            for app_config in apps.get_app_configs():
                indexes_path = "{}.extensions".format(app_config.name)
                try:
                    import_module(indexes_path)
                except ImportError:
                    pass

            self._discovery_done = True
        except Exception:
            # Rollback state to prevent corrupted state on exceptions during import.
            self._extensions = previous_state
            raise 
示例4
def sequence_list(self):
        "Returns a list of information about all DB sequences for all models in all apps."
        from django.apps import apps
        from django.db import models, router

        sequence_list = []

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                for f in model._meta.local_fields:
                    if isinstance(f, models.AutoField):
                        sequence_list.append({'table': model._meta.db_table, 'column': f.column})
                        break  # Only one AutoField is allowed per model, so don't bother continuing.

                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.rel.through is None:
                        sequence_list.append({'table': f.m2m_db_table(), 'column': None})

        return sequence_list 
示例5
def get_app_template_dirs(dirname):
    """
    Return an iterable of paths of directories to load app templates from.

    dirname is the name of the subdirectory containing templates inside
    installed applications.
    """
    template_dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path:
            continue
        template_dir = os.path.join(app_config.path, dirname)
        if os.path.isdir(template_dir):
            template_dirs.append(upath(template_dir))
    # Immutable return value because it will be cached and shared by callers.
    return tuple(template_dirs) 
示例6
def get_templatetags_modules():
    """
    Return the list of all available template tag modules.

    Caches the result for faster access.
    """
    templatetags_modules_candidates = ['django.templatetags']
    templatetags_modules_candidates.extend(
        '%s.templatetags' % app_config.name
        for app_config in apps.get_app_configs())

    templatetags_modules = []
    for templatetag_module in templatetags_modules_candidates:
        try:
            import_module(templatetag_module)
        except ImportError:
            continue
        else:
            templatetags_modules.append(templatetag_module)
    return templatetags_modules 
示例7
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app_config in apps.get_app_configs():
                try:
                    resource = resource_string(app_config.name, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(self.engine.file_charset)
                return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
        raise TemplateDoesNotExist(template_name) 
示例8
def __init__(self, app_names=None, *args, **kwargs):
        # The list of apps that are handled
        self.apps = []
        # Mapping of app names to storage instances
        self.storages = OrderedDict()
        app_configs = apps.get_app_configs()
        if app_names:
            app_names = set(app_names)
            app_configs = [ac for ac in app_configs if ac.name in app_names]
        for app_config in app_configs:
            app_storage = self.storage_class(
                os.path.join(app_config.path, self.source_dir))
            if os.path.isdir(app_storage.location):
                self.storages[app_config.name] = app_storage
                if app_config.name not in self.apps:
                    self.apps.append(app_config.name)
        super(AppDirectoriesFinder, self).__init__(*args, **kwargs) 
示例9
def emit_pre_migrate_signal(create_models, verbosity, interactive, db):
    # Emit the pre_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running pre-migrate handlers for application %s" % app_config.label)
        models.signals.pre_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db)
        # For backwards-compatibility -- remove in Django 1.9.
        models.signals.pre_syncdb.send(
            sender=app_config.models_module,
            app=app_config.models_module,
            create_models=create_models,
            verbosity=verbosity,
            interactive=interactive,
            db=db) 
示例10
def emit_post_migrate_signal(created_models, verbosity, interactive, db):
    # Emit the post_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running post-migrate handlers for application %s" % app_config.label)
        models.signals.post_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db)
        # For backwards-compatibility -- remove in Django 1.9.
        models.signals.post_syncdb.send(
            sender=app_config.models_module,
            app=app_config.models_module,
            created_models=created_models,
            verbosity=verbosity,
            interactive=interactive,
            db=db) 
示例11
def sequence_list(self):
        """
        Return a list of information about all DB sequences for all models in
        all apps.
        """
        from django.apps import apps
        from django.db import router

        sequence_list = []
        cursor = self.connection.cursor()

        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                if model._meta.swapped:
                    continue
                sequence_list.extend(self.get_sequences(cursor, model._meta.db_table, model._meta.local_fields))
                for f in model._meta.local_many_to_many:
                    # If this is an m2m using an intermediate table,
                    # we don't need to reset the sequence.
                    if f.remote_field.through is None:
                        sequence = self.get_sequences(cursor, f.m2m_db_table())
                        sequence_list.extend(sequence if sequence else [{'table': f.m2m_db_table(), 'column': None}])
        return sequence_list 
示例12
def get_app_template_dirs(dirname):
    """
    Return an iterable of paths of directories to load app templates from.

    dirname is the name of the subdirectory containing templates inside
    installed applications.
    """
    template_dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path:
            continue
        template_dir = os.path.join(app_config.path, dirname)
        if os.path.isdir(template_dir):
            template_dirs.append(template_dir)
    # Immutable return value because it will be cached and shared by callers.
    return tuple(template_dirs) 
示例13
def get_installed_libraries():
    """
    Return the built-in template tag libraries and those from installed
    applications. Libraries are stored in a dictionary where keys are the
    individual module names, not the full module paths. Example:
    django.templatetags.i18n is stored as i18n.
    """
    libraries = {}
    candidates = ['django.templatetags']
    candidates.extend(
        '%s.templatetags' % app_config.name
        for app_config in apps.get_app_configs())

    for candidate in candidates:
        try:
            pkg = import_module(candidate)
        except ImportError:
            # No templatetags package defined. This is safe to ignore.
            continue

        if hasattr(pkg, '__path__'):
            for name in get_package_libraries(pkg):
                libraries[name[len(candidate) + 1:]] = name

    return libraries 
示例14
def __init__(self, app_names=None, *args, **kwargs):
        # The list of apps that are handled
        self.apps = []
        # Mapping of app names to storage instances
        self.storages = OrderedDict()
        app_configs = apps.get_app_configs()
        if app_names:
            app_names = set(app_names)
            app_configs = [ac for ac in app_configs if ac.name in app_names]
        for app_config in app_configs:
            app_storage = self.storage_class(
                os.path.join(app_config.path, self.source_dir))
            if os.path.isdir(app_storage.location):
                self.storages[app_config.name] = app_storage
                if app_config.name not in self.apps:
                    self.apps.append(app_config.name)
        super().__init__(*args, **kwargs) 
示例15
def get_config_context():
    from django.apps import apps
    import importlib
    from app.db_manager.config_manager import get_config_by_name

    result = {}

    for app in apps.get_app_configs():
        deeru_config = getattr(app, 'deeru_config_context', None)
        if deeru_config:
            deeru_config = deeru_config.split('.')
            module_name = '.'.join(deeru_config[:-1])
            consts = importlib.import_module(module_name)
            app_config = getattr(consts, deeru_config[-1], {})
            for k, v in app_config.items():
                config = get_config_by_name(v)
                if config:
                    result[k] = config.v2_real_config
    return result 
示例16
def get_installed_apps():
    """
    Return list of all installed apps
    """
    if django.VERSION >= (1, 7):
        from django.apps import apps

        return [
            a.models_module
            for a in apps.get_app_configs()
            if a.models_module is not None
        ]
    else:
        from django.db import models

        return models.get_apps() 
示例17
def load_importer_modules():
    """
    Import .importers for each app in INSTALLED_APPS
    """
    global _importers_loaded

    if _importers_loaded:
        return

    for app_cfg in apps.get_app_configs():
        module_name = '%s.%s' % (app_cfg.name, 'importers')

        try:
            import_module(module_name)
        except ImportError:
            logger.warning("Importing %s app importers %s module",
                           app_cfg.name, module_name)

    _importers_loaded = True 
示例18
def __init__(self, snippets=None, resources=None):
        super(DjangoSquealy, self).__init__(snippets=snippets, resources=resources)
        for conn_name in connections:
            self.add_engine(conn_name, DjangoORMEngine(conn_name))
        
        resource_dirs = []
        for app_config in apps.get_app_configs():
            name = app_config.name
            if name.startswith('django.contrib.') or name in ('rest_framework', ):
                continue
            resource_dirs.append(app_config.path)
        if resource_dirs:
            logger.info("Loading resource files from these directories - %s", resource_dirs)
            self.load_objects(resource_dirs)
        else:
            logger.warn("Did not find any directories to load resources!") 
示例19
def get_dirs(self):
        project_app_dirs = []
        other_app_dirs = []

        for app_config in apps.get_app_configs():
            if not app_config.path:
                continue
            template_dir = os.path.join(app_config.path, 'templates')
            if os.path.isdir(template_dir):
                if app_config.name.startswith('apps.'):
                    project_app_dirs.append(upath(template_dir))
                    project_admin_template_dir = os.path.join(app_config.path, 'templates_admin')
                    if os.path.isdir(project_admin_template_dir):
                        project_app_dirs.append(upath(project_admin_template_dir))
                else:
                    other_app_dirs.append(upath(template_dir))
        project_dir = [os.path.join(str(settings.PROJECT_DIR), 'templates')]
        root_app_dir = [settings.APPS_DIR]

        # Immutable return value because it will be cached and shared by callers.
        return tuple(project_app_dirs + root_app_dir + project_dir + other_app_dirs) 
示例20
def sequence_list(self):
        """
        Return a list of information about all DB sequences for all models in
        all apps.
        """
        from django.apps import apps
        from django.db import router

        sequence_list = []
        with self.connection.cursor() as cursor:
            for app_config in apps.get_app_configs():
                for model in router.get_migratable_models(app_config, self.connection.alias):
                    if not model._meta.managed:
                        continue
                    if model._meta.swapped:
                        continue
                    sequence_list.extend(self.get_sequences(cursor, model._meta.db_table, model._meta.local_fields))
                    for f in model._meta.local_many_to_many:
                        # If this is an m2m using an intermediate table,
                        # we don't need to reset the sequence.
                        if f.remote_field.through is None:
                            sequence = self.get_sequences(cursor, f.m2m_db_table())
                            sequence_list.extend(sequence or [{'table': f.m2m_db_table(), 'column': None}])
        return sequence_list 
示例21
def __init__(self, app_names=None, *args, **kwargs):
        # The list of apps that are handled
        self.apps = []
        # Mapping of app names to storage instances
        self.storages = OrderedDict()
        app_configs = apps.get_app_configs()
        if app_names:
            app_names = set(app_names)
            app_configs = [ac for ac in app_configs if ac.name in app_names]
        for app_config in app_configs:
            app_storage = self.storage_class(
                os.path.join(app_config.path, self.source_dir))
            if os.path.isdir(app_storage.location):
                self.storages[app_config.name] = app_storage
                if app_config.name not in self.apps:
                    self.apps.append(app_config.name)
        super().__init__(*args, **kwargs) 
示例22
def clean_app_config(app_path):
    """
    Removes the AppConfig path for this app and returns the new string
    """
    apps_names = [app.name for app in apps.get_app_configs()]
    if app_path in apps_names:
        return app_path
    else:
        app_split = app_path.split('.')
        new_app = '.'.join(app_split[:-2])
        if new_app in apps_names:
            return new_app
        else:  # pragma: no cover
            raise ImproperlyConfigured(
                "The application {0} is not in the configured apps or does" +
                "not have the pattern app.apps.AppConfig".format(app_path)
            ) 
示例23
def _find_folders(self, folder_name):
        """Return a list of sub-directories."""
        found_folders = []
        for app_config in apps.get_app_configs():
            folder_path = os.path.join(app_config.path, folder_name)
            if os.path.isdir(folder_path):
                found_folders.append(folder_path)
        return found_folders 
示例24
def autodiscover_modules(*args, **kwargs):
    """
    Auto-discover INSTALLED_APPS modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.

    You may provide a register_to keyword parameter as a way to access a
    registry. This register_to object must have a _registry instance variable
    to access it.
    """
    from django.apps import apps

    register_to = kwargs.get('register_to')
    for app_config in apps.get_app_configs():
        for module_to_search in args:
            # Attempt to import the app's module.
            try:
                if register_to:
                    before_import_registry = copy.copy(register_to._registry)

                import_module('%s.%s' % (app_config.name, module_to_search))
            except:
                # Reset the registry to the state before the last import
                # as this import will have to reoccur on the next request and
                # this could raise NotRegistered and AlreadyRegistered
                # exceptions (see #8245).
                if register_to:
                    register_to._registry = before_import_registry

                # Decide whether to bubble up this error. If the app just
                # doesn't have the module in question, we can ignore the error
                # attempting to import it, otherwise we want it to bubble up.
                if module_has_submodule(app_config.module, module_to_search):
                    raise 
示例25
def _add_installed_apps_translations(self):
        """Merges translations from each installed app."""
        try:
            app_configs = reversed(list(apps.get_app_configs()))
        except AppRegistryNotReady:
            raise AppRegistryNotReady(
                "The translation infrastructure cannot be initialized before the "
                "apps registry is ready. Check that you don't make non-lazy "
                "gettext calls at import time.")
        for app_config in app_configs:
            localedir = os.path.join(app_config.path, 'locale')
            translation = self._new_gnu_trans(localedir)
            self.merge(translation) 
示例26
def serialize_db_to_string(self):
        """
        Serializes all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (not model._meta.proxy and model._meta.managed and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    for obj in queryset.iterator():
                        yield obj
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue() 
示例27
def django_table_names(self, only_existing=False, include_views=True):
        """
        Returns a list of all table names that have associated Django models and
        are in INSTALLED_APPS.

        If only_existing is True, the resulting list will only include the tables
        that actually exist in the database.
        """
        from django.apps import apps
        from django.db import router
        tables = set()
        for app_config in apps.get_app_configs():
            for model in router.get_migratable_models(app_config, self.connection.alias):
                if not model._meta.managed:
                    continue
                tables.add(model._meta.db_table)
                tables.update(f.m2m_db_table() for f in model._meta.local_many_to_many)
        tables = list(tables)
        if only_existing:
            existing_tables = self.table_names(include_views=include_views)
            tables = [
                t
                for t in tables
                if self.table_name_converter(t) in existing_tables
            ]
        return tables 
示例28
def fixture_dirs(self):
        """
        Return a list of fixture directories.

        The list contains the 'fixtures' subdirectory of each installed
        application, if it exists, the directories in FIXTURE_DIRS, and the
        current directory.
        """
        dirs = []
        fixture_dirs = settings.FIXTURE_DIRS
        if len(fixture_dirs) != len(set(fixture_dirs)):
            raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.")
        for app_config in apps.get_app_configs():
            app_label = app_config.label
            app_dir = os.path.join(app_config.path, 'fixtures')
            if app_dir in fixture_dirs:
                raise ImproperlyConfigured(
                    "'%s' is a default fixture directory for the '%s' app "
                    "and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label)
                )

            if self.app_label and app_label != self.app_label:
                continue
            if os.path.isdir(app_dir):
                dirs.append(app_dir)
        dirs.extend(list(fixture_dirs))
        dirs.append('')
        dirs = [upath(os.path.abspath(os.path.realpath(d))) for d in dirs]
        return dirs 
示例29
def get_commands():
    """
    Returns a dictionary mapping command names to their callback applications.

    This works by looking for a management.commands package in django.core, and
    in each installed application -- if a commands package exists, all commands
    in that package are registered.

    Core commands are always included. If a settings module has been
    specified, user-defined commands will also be included.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
示例30
def ready(self):
        installed_apps = [app_config.name for app_config in apps.get_app_configs()]
        app.autodiscover_tasks(lambda: installed_apps, force=True)