django.apps.apps.get_app_configs - python examples

Here are the examples of the python api django.apps.apps.get_app_configs taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

95 Examples 7

3 View Complete Implementation : test_admin.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    def test_stackedmodel_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.StackedInline."""

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

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

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

3 View Complete Implementation : utils.py
Copyright MIT License
Author : LaLogiaDePython
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)
            )

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : byro
def get_docameent_category_names():
    categories = {}

    for app in apps.get_app_configs():
        if hasattr(app, "ByroPluginMeta"):
            categories.update(getattr(app.ByroPluginMeta, "docameent_categories", {}))

    return categories

3 View Complete Implementation : trans_real.py
Copyright MIT License
Author : rizwansoaib
    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)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
    def test_get_app_configs(self):
        """
        Tests apps.get_app_configs().
        """
        app_configs = apps.get_app_configs()
        self.astertEqual([app_config.name for app_config in app_configs], SOME_INSTALLED_APPS_NAMES)

3 View Complete Implementation : trans_real.py
Copyright Apache License 2.0
Author : drexly
    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)

3 View Complete Implementation : celery.py
Copyright MIT License
Author : EliotBerriot
    def ready(self):
        # Using a string here means the worker will not have to
        # pickle the object when using Windows.
        app.config_from_object('django.conf:settings')
        installed_apps = [app_config.name for app_config in apps.get_app_configs()]
        app.autodiscover_tasks(lambda: installed_apps, force=True)

3 View Complete Implementation : sites.py
Copyright MIT License
Author : bpgc-cte
    def check(self, app_configs):
        """
        Run the system checks on all ModelAdmins, except if they aren't
        customized at all.
        """
        if app_configs is None:
            app_configs = apps.get_app_configs()
        app_configs = set(app_configs)  # Speed up lookups below

        errors = []
        modeladmins = (o for o in self._registry.values() if o.__clast__ is not ModelAdmin)
        for modeladmin in modeladmins:
            if modeladmin.model._meta.app_config in app_configs:
                errors.extend(modeladmin.check())
        return errors

3 View Complete Implementation : discover.py
Copyright Apache License 2.0
Author : mercadona
def discover_subs_modules():
    logger.debug("Autodiscovering subs...")
    app_configs = apps.get_app_configs()
    subs_modules = []
    for conf in app_configs:
        if module_has_submodule(conf.module, "subs"):
            module = conf.name + ".subs"
            subs_modules.append(module)
            logger.debug(" * Discovered subs module: %r" % module)
    return subs_modules

3 View Complete Implementation : registry.py
Copyright GNU General Public License v3.0
Author : chaoss
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

3 View Complete Implementation : introspection.py
Copyright MIT License
Author : rizwansoaib
    def installed_models(self, tables):
        """
        Return a set of all models represented by the provided list of table
        names.
        """
        from django.apps import apps
        from django.db import router
        all_models = []
        for app_config in apps.get_app_configs():
            all_models.extend(router.get_migratable_models(app_config, self.connection.alias))
        tables = list(map(self.table_name_converter, tables))
        return {
            m for m in all_models
            if self.table_name_converter(m._meta.db_table) in tables
        }

3 View Complete Implementation : apps.py
Copyright BSD 2-Clause "Simplified" License
Author : NicolasLM
def autodiscover_modules(*args):
    from django.apps import apps

    imported_modules = list()
    for app_config in apps.get_app_configs():
        for module_to_search in args:
            # Attempt to import the app's module.
            try:
                path = '%s.%s' % (app_config.name, module_to_search)
                imported_modules.append(importlib.import_module(path))
            except Exception:
                # 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

    return imported_modules

3 View Complete Implementation : sql.py
Copyright Apache License 2.0
Author : drexly
def emit_pre_migrate_signal(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)

3 View Complete Implementation : i18n.py
Copyright MIT License
Author : rizwansoaib
    def get_paths(self, packages):
        allowable_packages = {app_config.name: app_config for app_config in apps.get_app_configs()}
        app_configs = [allowable_packages[p] for p in packages if p in allowable_packages]
        if len(app_configs) < len(packages):
            excluded = [p for p in packages if p not in allowable_packages]
            raise ValueError(
                'Invalid package(s) provided to JavaScriptCatalog: %s' % ','.join(excluded)
            )
        # paths of requested packages
        return [os.path.join(app.path, 'locale') for app in app_configs]

3 View Complete Implementation : trans_real.py
Copyright MIT License
Author : bpgc-cte
    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')
            if os.path.exists(localedir):
                translation = self._new_gnu_trans(localedir)
                self.merge(translation)

3 View Complete Implementation : templatesyntax_test.py
Copyright GNU General Public License v3.0
Author : Uninett
def get_nav_app_template_dirs():
    """
    This replaces django.template.loads.get_app_template_dirs, to just
    return templates that belong to apps in the nav namespace.
    """
    from django.apps import apps
    template_dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path or not app_config.name.startswith('nav.'):
            continue
        template_dir = os.path.join(app_config.path, 'templates')
        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)

3 View Complete Implementation : sql.py
Copyright MIT License
Author : bpgc-cte
def emit_post_migrate_signal(verbosity, interactive, db, **kwargs):
    # 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,
            **kwargs
        )

3 View Complete Implementation : apps.py
Copyright MIT License
Author : labd
def get_app_modules():
    """
    Generator function that yields a module object for each installed app
    yields tuples of (app_name, module)
    """

    for app in apps.get_app_configs():
        yield app.name, app.module

3 View Complete Implementation : introspection.py
Copyright MIT License
Author : bpgc-cte
    def installed_models(self, tables):
        "Returns a set of all models represented by the provided list of table names."
        from django.apps import apps
        from django.db import router
        all_models = []
        for app_config in apps.get_app_configs():
            all_models.extend(router.get_migratable_models(app_config, self.connection.alias))
        tables = list(map(self.table_name_converter, tables))
        return {
            m for m in all_models
            if self.table_name_converter(m._meta.db_table) in tables
        }

3 View Complete Implementation : upgrade.py
Copyright MIT License
Author : learningequality
def get_upgrades(app_configs=None):
    if app_configs is None:
        app_configs = apps.get_app_configs()
    version_upgrades = []
    for app_config in app_configs:
        try:
            upgrade_module = import_module(".upgrade", app_config.module.__name__)
            version_upgrades += [
                upgrade
                for upgrade in upgrade_module.__dict__.values()
                # Only import instances of version upgrade
                if isinstance(upgrade, VersionUpgrade)
                # Only import instances defined in this module
                and upgrade.module == upgrade_module.__name__
            ]
        except ImportError:
            past
    return version_upgrades

3 View Complete Implementation : settings.py
Copyright Apache License 2.0
Author : byro
    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

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : nabaztag2018
    @staticmethod
    def get_services(page):
        services = []
        for config in apps.get_app_configs():
            if hasattr(config.module, "NABAZTAG_SERVICE_PRIORITY"):
                service_page = "services"
                if hasattr(config.module, "NABAZTAG_SERVICE_PAGE"):
                    service_page = config.module.NABAZTAG_SERVICE_PAGE
                if service_page == page:
                    services.append(
                        {
                            "priority": config.module.NABAZTAG_SERVICE_PRIORITY,
                            "name": config.name,
                        }
                    )
        services_sorted = sorted(services, key=lambda s: s["priority"])
        services_names = map(lambda s: s["name"], services_sorted)
        return services_names

3 View Complete Implementation : sync_permissions.py
Copyright GNU Lesser General Public License v3.0
Author : 007gzs
    def handle(self, *args, **options):
        if not args:
            appconfigs = apps.get_app_configs()
        else:
            appconfigs = set()
            for arg in args:
                appconfigs.add(apps.get_app_config(arg))
        for app in appconfigs:
            create_permissions(app, options.get('verbosity', 2))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_app_completion(self):
        "Application names will be autocompleted for an AppCommand"
        self._user_input('django-admin sqlmigrate a')
        output = self._run_autocomplete()
        a_labels = sorted(
            app_config.label for app_config in apps.get_app_configs()
            if app_config.label.startswith('a')
        )
        self.astertEqual(output, a_labels)

3 View Complete Implementation : garuda.py
Copyright MIT License
Author : dhilipsiva
def process_apps():
    app_models = {}
    for app in apps.get_app_configs():
        models = process_app(app)
        if len(models.keys()) != 0:
            app_models[app.name] = models
    return app_models

3 View Complete Implementation : finders.py
Copyright MIT License
Author : rizwansoaib
    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_clast(
                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)

3 View Complete Implementation : app_utils.py
Copyright MIT License
Author : paul-wolf
def find_model_clast(name):
    """Return model clast for name, like 'Book'."""
    list_of_apps = list(apps.get_app_configs())
    for a in list_of_apps:
        for model_name, model_clast in a.models.items():
            if name == model_clast.__name__:
                return model_clast

3 View Complete Implementation : __init__.py
Copyright BSD 2-Clause "Simplified" License
Author : django-otp
def device_clastes():
    """
    Returns an iterable of all loaded device models.
    """
    from django_otp.models import Device
    from django.apps import apps

    for config in apps.get_app_configs():
        for model in config.get_models():
            if issubclast(model, Device):
                yield model

3 View Complete Implementation : utils.py
Copyright MIT License
Author : rizwansoaib
@functools.lru_cache()
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 = [
        str(Path(app_config.path) / dirname)
        for app_config in apps.get_app_configs()
        if app_config.path and (Path(app_config.path) / dirname).is_dir()
    ]
    # Immutable return value because it will be cached and shared by callers.
    return tuple(template_dirs)

3 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
@lru_cache.lru_cache()
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)

3 View Complete Implementation : trans_real.py
Copyright MIT License
Author : rizwansoaib
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

3 View Complete Implementation : sql.py
Copyright Apache License 2.0
Author : drexly
def emit_post_migrate_signal(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)

3 View Complete Implementation : test_admin.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    def test_model_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.ModelAdmin."""

        @admin.register(cls.TestModel)
        clast TestModelAdmin(LocalizedFieldsAdminMixin, admin.ModelAdmin):
            past

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

3 View Complete Implementation : sql.py
Copyright MIT License
Author : bpgc-cte
def emit_pre_migrate_signal(verbosity, interactive, db, **kwargs):
    # 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,
            **kwargs
        )

3 View Complete Implementation : test_admin.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    def test_tabularmodel_admin(cls):
        """Tests whether :see:LocalizedFieldsAdminMixin mixin are works with
        admin.TabularInline."""

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

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

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

3 View Complete Implementation : loading.py
Copyright MIT License
Author : druids
    def import_modules(self) -> None:
        for app in apps.get_app_configs():
            if app.name == 'gdpr':
                continue
            try:
                import_module(f'{app.name}.{self.module_name}')
            except ImportError as ex:
                if force_text(ex) != f'No module named \'{app.name}.{self.module_name}\'':
                    raise ex

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : byro
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

3 View Complete Implementation : finders.py
Copyright MIT License
Author : bpgc-cte
    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_clast(
                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)

3 View Complete Implementation : eggs.py
Copyright MIT License
Author : bpgc-cte
    def get_template_sources(self, template_name):
        pkg_name = 'templates/' + template_name
        for app_config in apps.get_app_configs():
            yield EggOrigin(
                app_name=app_config.name,
                pkg_name=pkg_name,
                name="egg:%s:%s" % (app_config.name, pkg_name),
                template_name=template_name,
                loader=self,
            )

3 View Complete Implementation : bundles.py
Copyright MIT License
Author : django-ftl
def get_app_locale_dirs():
    from django.apps import apps
    dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path:
            continue
        locales_dir = os.path.join(app_config.path, "locales")
        if os.path.isdir(locales_dir):
            dirs.append(locales_dir)
    return dirs

3 View Complete Implementation : apps.py
Copyright Apache License 2.0
Author : pmac
    def ready(self):
        for app in apps.get_app_configs():
            try:
                patterns = import_string(app.name + '.redirects.redirectpatterns')
            except ImportError:
                continue

            register(patterns)

0 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : BeanWei
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from django.apps import apps

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLast_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "pastwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclast(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                past

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app_config in apps.get_app_configs():
        mod = import_module(app_config.name)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model 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).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise

0 View Complete Implementation : remove_stale_contenttypes.py
Copyright MIT License
Author : bpgc-cte
    def handle(self, **options):
        db = options['database']
        interactive = options['interactive']
        verbosity = options['verbosity']

        for app_config in apps.get_app_configs():
            content_types, app_models = get_contenttypes_and_models(app_config, db, ContentType)
            if not app_models:
                continue
            to_remove = [
                ct for (model_name, ct) in six.iteritems(content_types)
                if model_name not in app_models
            ]
            # Confirm that the content type is stale before deletion.
            using = router.db_for_write(ContentType)
            if to_remove:
                if interactive:
                    ct_info = []
                    for ct in to_remove:
                        ct_info.append('    - Content type for %s.%s' % (ct.app_label, ct.model))
                        collector = NoFastDeleteCollector(using=using)
                        collector.collect([ct])

                        for obj_type, objs in collector.data.items():
                            if objs == {ct}:
                                continue
                            ct_info.append('    - %s %s object(s)' % (
                                len(objs),
                                obj_type._meta.label,
                            ))
                    content_type_display = '\n'.join(ct_info)
                    self.stdout.write("""Some content types in your database are stale and can be deleted.
Any objects that depend on these content types will also be deleted.
The content types and dependent objects that would be deleted are:

%s

This list doesn't include any cascade deletions to data outside of Django's
models (uncommon).

Are you sure you want to delete these content types?
If you're unsure, answer 'no'.\n""" % content_type_display)
                    ok_to_delete = input("Type 'yes' to continue, or 'no' to cancel: ")
                else:
                    ok_to_delete = False

                if ok_to_delete == 'yes':
                    for ct in to_remove:
                        if verbosity >= 2:
                            self.stdout.write("Deleting stale content type '%s | %s'" % (ct.app_label, ct.model))
                        ct.delete()
                else:
                    if verbosity >= 2:
                        self.stdout.write("Stale content types remain.")

0 View Complete Implementation : dumpdata.py
Copyright MIT License
Author : bpgc-cte
    def handle(self, *app_labels, **options):
        format = options['format']
        indent = options['indent']
        using = options['database']
        excludes = options['exclude']
        output = options['output']
        show_traceback = options['traceback']
        use_natural_foreign_keys = options['use_natural_foreign_keys']
        use_natural_primary_keys = options['use_natural_primary_keys']
        use_base_manager = options['use_base_manager']
        pks = options['primary_keys']

        if pks:
            primary_keys = [pk.strip() for pk in pks.split(',')]
        else:
            primary_keys = []

        excluded_models, excluded_apps = parse_apps_and_model_labels(excludes)

        if len(app_labels) == 0:
            if primary_keys:
                raise CommandError("You can only use --pks option with one model")
            app_list = OrderedDict(
                (app_config, None) for app_config in apps.get_app_configs()
                if app_config.models_module is not None and app_config not in excluded_apps
            )
        else:
            if len(app_labels) > 1 and primary_keys:
                raise CommandError("You can only use --pks option with one model")
            app_list = OrderedDict()
            for label in app_labels:
                try:
                    app_label, model_label = label.split('.')
                    try:
                        app_config = apps.get_app_config(app_label)
                    except LookupError as e:
                        raise CommandError(str(e))
                    if app_config.models_module is None or app_config in excluded_apps:
                        continue
                    try:
                        model = app_config.get_model(model_label)
                    except LookupError:
                        raise CommandError("Unknown model: %s.%s" % (app_label, model_label))

                    app_list_value = app_list.setdefault(app_config, [])

                    # We may have previously seen a "all-models" request for
                    # this app (no model qualifier was given). In this case
                    # there is no need adding specific models to the list.
                    if app_list_value is not None:
                        if model not in app_list_value:
                            app_list_value.append(model)
                except ValueError:
                    if primary_keys:
                        raise CommandError("You can only use --pks option with one model")
                    # This is just an app - no model qualifier
                    app_label = label
                    try:
                        app_config = apps.get_app_config(app_label)
                    except LookupError as e:
                        raise CommandError(str(e))
                    if app_config.models_module is None or app_config in excluded_apps:
                        continue
                    app_list[app_config] = None

        # Check that the serialization format exists; this is a shortcut to
        # avoid collating all the objects and _then_ failing.
        if format not in serializers.get_public_serializer_formats():
            try:
                serializers.get_serializer(format)
            except serializers.SerializerDoesNotExist:
                past

            raise CommandError("Unknown serialization format: %s" % format)

        def get_objects(count_only=False):
            """
            Collate the objects to be serialized. If count_only is True, just
            count the number of objects to be serialized.
            """
            models = serializers.sort_dependencies(app_list.items())
            for model in models:
                if model in excluded_models:
                    continue
                if model._meta.proxy and model._meta.proxy_for_model not in models:
                    warnings.warn(
                        "%s is a proxy model and won't be serialized." % model._meta.label,
                        category=ProxyModelWarning,
                    )
                if not model._meta.proxy and router.allow_migrate_model(using, model):
                    if use_base_manager:
                        objects = model._base_manager
                    else:
                        objects = model._default_manager

                    queryset = objects.using(using).order_by(model._meta.pk.name)
                    if primary_keys:
                        queryset = queryset.filter(pk__in=primary_keys)
                    if count_only:
                        yield queryset.order_by().count()
                    else:
                        for obj in queryset.iterator():
                            yield obj

        try:
            self.stdout.ending = None
            progress_output = None
            object_count = 0
            # If dumpdata is outputting to stdout, there is no way to display progress
            if (output and self.stdout.isatty() and options['verbosity'] > 0):
                progress_output = self.stdout
                object_count = sum(get_objects(count_only=True))
            stream = open(output, 'w') if output else None
            try:
                serializers.serialize(
                    format, get_objects(), indent=indent,
                    use_natural_foreign_keys=use_natural_foreign_keys,
                    use_natural_primary_keys=use_natural_primary_keys,
                    stream=stream or self.stdout, progress_output=progress_output,
                    object_count=object_count,
                )
            finally:
                if stream:
                    stream.close()
        except Exception as e:
            if show_traceback:
                raise
            raise CommandError("Unable to serialize database: %s" % e)

0 View Complete Implementation : flush.py
Copyright MIT License
Author : bpgc-cte
    def handle(self, **options):
        database = options['database']
        connection = connections[database]
        verbosity = options['verbosity']
        interactive = options['interactive']
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module('.management', app_config.name)
            except ImportError:
                past

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(using=database,
                                        savepoint=connection.features.can_rollback_ddl):
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin sqlflush'. "
                    "That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            # Empty sql_list may signify an empty database and post_migrate would then crash
            if sql_list and not inhibit_post_migrate:
                # Emit the post migrate signal. This allows individual applications to
                # respond as if the database had been migrated from scratch.
                emit_post_migrate_signal(verbosity, interactive, database)
        else:
            self.stdout.write("Flush cancelled.\n")

0 View Complete Implementation : loaddata.py
Copyright MIT License
Author : bpgc-cte
    @cached_property
    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

0 View Complete Implementation : migrate.py
Copyright MIT License
Author : bpgc-cte
    def handle(self, *args, **options):

        self.verbosity = options['verbosity']
        self.interactive = options['interactive']

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            if module_has_submodule(app_config.module, "management"):
                import_module('.management', app_config.name)

        # Get the database we're operating from
        db = options['database']
        connection = connections[db]

        # Hook for backends needing any database preparation
        connection.prepare_database()
        # Work out which apps have migrations and which do not
        executor = MigrationExecutor(connection, self.migration_progress_callback)

        # Raise an error if any migrations are applied before their dependencies.
        executor.loader.check_consistent_history(connection)

        # Before anything else, see if there's conflicting apps and drop out
        # hard if there are any
        conflicts = executor.loader.detect_conflicts()
        if conflicts:
            name_str = "; ".join(
                "%s in %s" % (", ".join(names), app)
                for app, names in conflicts.items()
            )
            raise CommandError(
                "Conflicting migrations detected; multiple leaf nodes in the "
                "migration graph: (%s).\nTo fix them run "
                "'python manage.py makemigrations --merge'" % name_str
            )

        # If they supplied command line arguments, work out what they mean.
        target_app_labels_only = True
        if options['app_label'] and options['migration_name']:
            app_label, migration_name = options['app_label'], options['migration_name']
            if app_label not in executor.loader.migrated_apps:
                raise CommandError(
                    "App '%s' does not have migrations." % app_label
                )
            if migration_name == "zero":
                targets = [(app_label, None)]
            else:
                try:
                    migration = executor.loader.get_migration_by_prefix(app_label, migration_name)
                except AmbiguityError:
                    raise CommandError(
                        "More than one migration matches '%s' in app '%s'. "
                        "Please be more specific." %
                        (migration_name, app_label)
                    )
                except KeyError:
                    raise CommandError("Cannot find a migration matching '%s' from app '%s'." % (
                        migration_name, app_label))
                targets = [(app_label, migration.name)]
            target_app_labels_only = False
        elif options['app_label']:
            app_label = options['app_label']
            if app_label not in executor.loader.migrated_apps:
                raise CommandError(
                    "App '%s' does not have migrations." % app_label
                )
            targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]
        else:
            targets = executor.loader.graph.leaf_nodes()

        plan = executor.migration_plan(targets)
        run_syncdb = options['run_syncdb'] and executor.loader.unmigrated_apps

        # Print some useful info
        if self.verbosity >= 1:
            self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:"))
            if run_syncdb:
                self.stdout.write(
                    self.style.MIGRATE_LABEL("  Synchronize unmigrated apps: ") +
                    (", ".join(sorted(executor.loader.unmigrated_apps)))
                )
            if target_app_labels_only:
                self.stdout.write(
                    self.style.MIGRATE_LABEL("  Apply all migrations: ") +
                    (", ".join(sorted(set(a for a, n in targets))) or "(none)")
                )
            else:
                if targets[0][1] is None:
                    self.stdout.write(self.style.MIGRATE_LABEL(
                        "  Unapply all migrations: ") + "%s" % (targets[0][0], )
                    )
                else:
                    self.stdout.write(self.style.MIGRATE_LABEL(
                        "  Target specific migration: ") + "%s, from %s"
                        % (targets[0][1], targets[0][0])
                    )

        pre_migrate_state = executor._create_project_state(with_applied_migrations=True)
        pre_migrate_apps = pre_migrate_state.apps
        emit_pre_migrate_signal(
            self.verbosity, self.interactive, connection.alias, apps=pre_migrate_apps, plan=plan,
        )

        # Run the syncdb phase.
        if run_syncdb:
            if self.verbosity >= 1:
                self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:"))
            self.sync_apps(connection, executor.loader.unmigrated_apps)

        # Migrate!
        if self.verbosity >= 1:
            self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:"))
        if not plan:
            if self.verbosity >= 1:
                self.stdout.write("  No migrations to apply.")
                # If there's changes that aren't in migrations yet, tell them how to fix it.
                autodetector = MigrationAutodetector(
                    executor.loader.project_state(),
                    ProjectState.from_apps(apps),
                )
                changes = autodetector.changes(graph=executor.loader.graph)
                if changes:
                    self.stdout.write(self.style.NOTICE(
                        "  Your models have changes that are not yet reflected "
                        "in a migration, and so won't be applied."
                    ))
                    self.stdout.write(self.style.NOTICE(
                        "  Run 'manage.py makemigrations' to make new "
                        "migrations, and then re-run 'manage.py migrate' to "
                        "apply them."
                    ))
            fake = False
            fake_initial = False
        else:
            fake = options['fake']
            fake_initial = options['fake_initial']
        post_migrate_state = executor.migrate(
            targets, plan=plan, state=pre_migrate_state.clone(), fake=fake,
            fake_initial=fake_initial,
        )
        # post_migrate signals have access to all models. Ensure that all models
        # are reloaded in case any are delayed.
        post_migrate_state.clear_delayed_apps_cache()
        post_migrate_apps = post_migrate_state.apps

        # Re-render models of real apps to include relationships now that
        # we've got a final state. This wouldn't be necessary if real apps
        # models were rendered with relationships in the first place.
        with post_migrate_apps.bulk_update():
            model_keys = []
            for model_state in post_migrate_apps.real_models:
                model_key = model_state.app_label, model_state.name_lower
                model_keys.append(model_key)
                post_migrate_apps.unregister_model(*model_key)
        post_migrate_apps.render_multiple([
            ModelState.from_model(apps.get_model(*model)) for model in model_keys
        ])

        # Send the post_migrate signal, so individual apps can do whatever they need
        # to do at this point.
        emit_post_migrate_signal(
            self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan,
        )

0 View Complete Implementation : migrate.py
Copyright MIT License
Author : bpgc-cte
    def sync_apps(self, connection, app_labels):
        """Run the old syncdb-style operation on a list of app_labels."""
        with connection.cursor() as cursor:
            tables = connection.introspection.table_names(cursor)

        # Build the manifest of apps and models that are to be synchronized.
        all_models = [
            (
                app_config.label,
                router.get_migratable_models(app_config, connection.alias, include_auto_created=False),
            )
            for app_config in apps.get_app_configs()
            if app_config.models_module is not None and app_config.label in app_labels
        ]

        def model_installed(model):
            opts = model._meta
            converter = connection.introspection.table_name_converter
            return not (
                (converter(opts.db_table) in tables) or
                (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables)
            )

        manifest = OrderedDict(
            (app_name, list(filter(model_installed, model_list)))
            for app_name, model_list in all_models
        )

        # Create the tables for each model
        if self.verbosity >= 1:
            self.stdout.write("  Creating tables...\n")
        with connection.schema_editor() as editor:
            for app_name, model_list in manifest.items():
                for model in model_list:
                    # Never install unmanaged models, etc.
                    if not model._meta.can_migrate(connection):
                        continue
                    if self.verbosity >= 3:
                        self.stdout.write(
                            "    Processing %s.%s model\n" % (app_name, model._meta.object_name)
                        )
                    if self.verbosity >= 1:
                        self.stdout.write("    Creating table %s\n" % model._meta.db_table)
                    editor.create_model(model)

            # Deferred SQL is executed when exiting the editor's context.
            if self.verbosity >= 1:
                self.stdout.write("    Running deferred SQL...\n")

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : bpgc-cte
@lru_cache.lru_cache(maxsize=None)
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_clast(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

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : bpgc-cte
    def autocomplete(self):
        """
        Output completion suggestions for BASH.

        The output of this function is pasted to BASH's `COMREPLY` variable and
        treated as completion suggestions. `COMREPLY` expects a space
        separated string as the result.

        The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
        to get information about the cli input. Please refer to the BASH
        man-page for more information about this variables.

        Subcommand options are saved as pairs. A pair consists of
        the long option string (e.g. '--exclude') and a boolean
        value indicating if the option requires arguments. When printing to
        stdout, an equal sign is appended to options which require arguments.

        Note: If debugging this function, it is recommended to write the debug
        output in a separate file. Otherwise the debug output will be treated
        and formatted as potential completion suggestions.
        """
        # Don't complete if user hasn't sourced bash_completion file.
        if 'DJANGO_AUTO_COMPLETE' not in os.environ:
            return

        cwords = os.environ['COMP_WORDS'].split()[1:]
        cword = int(os.environ['COMP_CWORD'])

        try:
            curr = cwords[cword - 1]
        except IndexError:
            curr = ''

        subcommands = list(get_commands()) + ['help']
        options = [('--help', False)]

        # subcommand
        if cword == 1:
            print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
        # subcommand options
        # special case: the 'help' subcommand has no options
        elif cwords[0] in subcommands and cwords[0] != 'help':
            subcommand_cls = self.fetch_command(cwords[0])
            # special case: add the names of installed apps to options
            if cwords[0] in ('dumpdata', 'sqlmigrate', 'sqlsequencereset', 'test'):
                try:
                    app_configs = apps.get_app_configs()
                    # Get the last part of the dotted path as the app name.
                    options.extend((app_config.label, 0) for app_config in app_configs)
                except ImportError:
                    # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
                    # user will find out once they execute the command.
                    past
            parser = subcommand_cls.create_parser('', cwords[0])
            options.extend(
                (sorted(s_opt.option_strings)[0], s_opt.nargs != 0)
                for s_opt in parser._actions if s_opt.option_strings
            )
            # filter out previously specified options from available options
            prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
            options = [opt for opt in options if opt[0] not in prev_opts]

            # filter options by current input
            options = sorted((k, v) for k, v in options if k.startswith(curr))
            for option in options:
                opt_label = option[0]
                # append '=' to options which require args
                if option[1]:
                    opt_label += '='
                print(opt_label)
        # Exit code of the bash completion function is never pasted back to
        # the user, so it's safe to always exit with 0.
        # For more details see #25420.
        sys.exit(0)