Python django.apps.apps.get_app_configs() Examples

The following are 30 code examples of django.apps.apps.get_app_configs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.apps.apps , or try the search function .
Example #1
Source File: utils.py    From django-menu-generator with MIT License 6 votes vote down vote up
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)
            ) 
Example #2
Source File: __init__.py    From resolwe with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #4
Source File: composer.py    From resolwe with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: introspection.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #6
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #7
Source File: eggs.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #8
Source File: finders.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: composer.py    From resolwe with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: sql.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #11
Source File: sql.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #12
Source File: introspection.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #13
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: django.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #15
Source File: finders.py    From bioforum with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: __init__.py    From DeerU with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: utils.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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() 
Example #18
Source File: registry.py    From prospector with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #19
Source File: django.py    From squealy with MIT License 6 votes vote down vote up
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!") 
Example #20
Source File: loaders.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #21
Source File: introspection.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 
Example #22
Source File: finders.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #23
Source File: test_admin.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_stackedmodel_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.StackedInline."""

        class TestModelStackedInline(
            LocalizedFieldsAdminMixin, admin.StackedInline
        ):
            model = cls.TestModel

        @admin.register(cls.TestRelModel)
        class TestRelModelAdmin(admin.ModelAdmin):
            inlines = [TestModelStackedInline]

        assert len(check_admin_app(apps.get_app_configs())) == 0 
Example #24
Source File: utils.py    From byro with Apache License 2.0 5 votes vote down vote up
def get_plugins():
    result = []
    for app in apps.get_app_configs():
        if hasattr(app, "ByroPluginMeta"):
            if getattr(app, "name", "").startswith("byro.") and not hasattr(
                app.ByroPluginMeta, "version"
            ):
                continue
            result.append(app)
    return result 
Example #25
Source File: test_admin.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_model_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.ModelAdmin."""

        @admin.register(cls.TestModel)
        class TestModelAdmin(LocalizedFieldsAdminMixin, admin.ModelAdmin):
            pass

        assert len(check_admin_app(apps.get_app_configs())) == 0 
Example #26
Source File: settings.py    From byro with Apache License 2.0 5 votes vote down vote up
def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context["plugins"] = []
        for app in apps.get_app_configs():
            if hasattr(app, "ByroPluginMeta") and hasattr(app.ByroPluginMeta, "name"):
                context["plugins"].append({"meta": app.ByroPluginMeta})
        return context 
Example #27
Source File: trans_real.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _add_installed_apps_translations(self):
        """Merge 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')
            if os.path.exists(localedir):
                translation = self._new_gnu_trans(localedir)
                self.merge(translation) 
Example #28
Source File: trans_real.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def all_locale_paths():
    """
    Return a list of paths to user-provides languages files.
    """
    globalpath = os.path.join(
        os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
    app_paths = []
    for app_config in apps.get_app_configs():
        locale_path = os.path.join(app_config.path, 'locale')
        if os.path.exists(locale_path):
            app_paths.append(locale_path)
    return [globalpath] + list(settings.LOCALE_PATHS) + app_paths 
Example #29
Source File: creation.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def serialize_db_to_string(self):
        """
        Serialize 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 (model._meta.can_migrate(self.connection) and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    yield from queryset.iterator()
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue() 
Example #30
Source File: test_admin.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_tabularmodel_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.TabularInline."""

        class TestModelTabularInline(
            LocalizedFieldsAdminMixin, admin.TabularInline
        ):
            model = cls.TestModel

        @admin.register(cls.TestRelModel)
        class TestRelModelAdmin(admin.ModelAdmin):
            inlines = [TestModelTabularInline]

        assert len(check_admin_app(apps.get_app_configs())) == 0