我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.apps.apps.get_app_configs()。
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
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)
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.remote_field.through is None: sequence_list.append({'table': f.m2m_db_table(), 'column': None}) return sequence_list
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
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)
def ready(self): import inspect import importlib from django.apps import apps from .index import ALL_INDEXES, SphinxXMLIndex for appconf in apps.get_app_configs(): try: indexes_module = importlib.import_module('%s.indexes' % appconf.name) except ImportError: continue for name, member in inspect.getmembers(indexes_module, inspect.isclass): if member is SphinxXMLIndex or not issubclass(member, SphinxXMLIndex): continue if member.name in ALL_INDEXES: raise LookupError("Sphinx index with name '%s' already exists" % member.name) else: ALL_INDEXES[member.name] = member
def ready(self): for key, config in six.iteritems(settings.MODELCHEMY_DATABASES): if "URL" not in config: raise ImproperlyConfigured( "The database '%s' doesn't include a URL config." % ( key ) ) alias = key if "ALIAS" not in config else config["ALIAS"] dbs.set(alias, SiteDatabaseRecordFactory(config['URL'])) for app_config in apps.get_app_configs(): try: import_module(".%s.%s" % ( REQUEST_KEY, alias), app_config.name) except ImportError: continue configure_mappers() super(AppConfig, self).ready()
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)
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)
def autodiscover_authorizations(*args, **kwargs): """ Auto-discover authorization modules and fail silently when not present. This forces an import on them to register any authorization classes. 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 authorization's module. if register_to: before_import_registry = copy.copy(register_to._registry) try: import_module('{}.{}'.format(app_config.name, module_to_search)) except Exception: # Restore last registry on import error occurred if register_to: register_to._registry = before_import_registry
def missing_permissions(self): """ Permissions to create """ perms = [] for app_config in apps.get_app_configs(): perms += permissions.get_missing_permissions_for_app_config( app_config) return [ "INSERT INTO auth_permission(codename, name, content_type_id) " "VALUES('{}', '{}', (SELECT id FROM django_content_type " "WHERE app_label = '{}' AND model = '{}'));".format( perm.codename, perm.name, perm.content_type.app_label, perm.content_type.model) for perm in perms ]
def autodiscover_modules(*args, force_reload=True): """ An enhanced version of `django.utils.module_loading.autodiscover_modules`, which can force target modules to be reloaded. """ from django.apps import apps import sys for app_config in apps.get_app_configs(): for module_to_search in args: mod_name = '%s.%s' % (app_config.name, module_to_search) if force_reload: try: del sys.modules[mod_name] except KeyError: pass try: importlib.import_module(mod_name) except Exception: if module_has_submodule(app_config.module, module_to_search): raise
def _get_menu_templates(): """Get menu template names -> tuple Try to automatically find menu templates with the naming scheme <app>/menu.html in the apps and in the global settings.MENU_TEMPLATES tuple and return a tuple of them. """ menu_templates = cache.get('menu_templates') if menu_templates: return menu_templates menu_templates = [] for app in apps.get_app_configs(): for path in iglob('{}/templates/*/menu.html'.format(app.path)): menu_templates.append('/'.join(path.rsplit('/', 2)[-2:])) cache.set('menu_templates', menu_templates) return tuple(menu_templates)
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
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)
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)
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 (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) 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()
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
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 }
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, )
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)
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) {% if cookiecutter.use_sentry_for_error_reporting == 'y' -%} if hasattr(settings, 'RAVEN_CONFIG'): # Celery signal registration
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 )