Python源码示例:django.apps()

示例1
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() 
示例2
def test_get_fields_only_searches_forward_on_apps_not_ready(self):
        opts = CassandraThing._meta
        # If apps registry is not ready, get_field() searches over only
        # forward fields.
        opts.apps.models_ready = False
        try:
            # 'data_abstract' is a forward field, and therefore will be found
            self.assertTrue(opts.get_field('data_abstract'))
            msg = (
                "CassandraThing has no field named 'relating_baseperson'. The app "
                "cache isn't ready yet, so if this is an auto-created related "
                "field, it won't be available yet."
            )
            # 'data_abstract' is a reverse field, and will raise an exception
            with self.assertRaisesMessage(FieldDoesNotExist, msg):
                opts.get_field('relating_baseperson')
        finally:
            opts.apps.models_ready = True 
示例3
def setup_django():
    import django
    from django.conf import settings
    if not settings.configured:
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': ':memory:',
                }
            },
            INSTALLED_APPS=(
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django_ftpserver',
            )
        )
    django.setup()
    from django.apps import apps
    if not apps.ready:
        apps.populate() 
示例4
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
示例5
def mock_django_setup(settings_module, disabled_features=None):
    """ Must be called *AT IMPORT TIME* to pretend that Django is set up.

    This is useful for running tests without using the Django test runner.
    This must be called before any Django models are imported, or they will
    complain. Call this from a module in the calling project at import time,
    then be sure to import that module at the start of all mock test modules.
    Another option is to call it from the test package's init file, so it runs
    before all the test modules are imported.
    :param settings_module: the module name of the Django settings file,
        like 'myapp.settings'
    :param disabled_features: a list of strings that should be marked as
        *False* on the connection features list. All others will default
        to True.
    """
    if apps.ready:
        # We're running in a real Django unit test, don't do anything.
        return

    if 'DJANGO_SETTINGS_MODULE' not in os.environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
    django.setup()
    mock_django_connection(disabled_features) 
示例6
def test_install_middleware_old_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

    with override_settings(MIDDLEWARE_CLASSES=middleware):
        apps.get_app_config("scout_apm").install_middleware()

        assert settings.MIDDLEWARE_CLASSES == list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        ) 
示例7
def test_install_middleware_new_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

    with override_settings(MIDDLEWARE=middleware):
        apps.get_app_config("scout_apm").install_middleware()

        assert settings.MIDDLEWARE == list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        ) 
示例8
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.listdir(dirpath):
            if ('.' in f or
                    os.path.basename(f) in SUBDIRS_TO_SKIP or
                    os.path.isfile(f) or
                    not os.path.exists(os.path.join(dirpath, f, '__init__.py'))):
                continue
            modules.append((modpath, f))
    return modules 
示例9
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
示例10
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.listdir(dirpath):
            if ('.' not in f and
                    os.path.basename(f) not in SUBDIRS_TO_SKIP and
                    not os.path.isfile(f) and
                    os.path.exists(os.path.join(dirpath, f, '__init__.py'))):
                modules.append((modpath, f))
    return modules 
示例11
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
示例12
def test_migrate_to_form_question_natural_key_reverse(transactional_db):
    executor = MigrationExecutor(connection)
    app = "caluma_form"
    migrate_from = [(app, "0024_auto_20190919_1244")]
    migrate_to = [(app, "0023_auto_20190729_1448")]

    executor.migrate(migrate_from)
    old_apps = executor.loader.project_state(migrate_from).apps

    # Create some old data. Can't use factories here

    Form = old_apps.get_model(app, "Form")
    Question = old_apps.get_model(app, "Question")
    FormQuestion = old_apps.get_model(app, "FormQuestion")

    form_1 = Form.objects.create(slug="form-1")

    question_1 = Question.objects.create(type="text", slug="question-1")
    FormQuestion.objects.create(form=form_1, question=question_1)

    # Migrate backwards.
    executor.loader.build_graph()  # reload.
    with pytest.raises(DataError):
        executor.migrate(migrate_to) 
示例13
def get_commands():
    """
    Returns a dictionary mapping command names to their callback applications.

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

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

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

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

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

    if not settings.configured:
        return commands

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

    return commands 
示例14
def handle(self, *app_labels, **options):
        from django.apps import apps
        try:
            app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
        except (LookupError, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        output = []
        for app_config in app_configs:
            app_output = self.handle_app_config(app_config, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output) 
示例15
def setUp(self):
        # Taken from IsolatedModelsTestCase in
        # django/tests/invalid_models_tests/base.py
        from django.apps import apps

        self._old_models = apps.app_configs["tests"].models.copy() 
示例16
def tearDown(self):
        # Taken from IsolatedModelsTestCase in
        # django/tests/invalid_models_tests/base.py
        from django.apps import apps

        apps.app_configs["tests"].models = self._old_models
        apps.all_models["tests"] = self._old_models
        apps.clear_cache() 
示例17
def is_installed(appname):
        return appname in settings.INSTALLED_APPS #or apps.is_installed(appname) 
示例18
def get_django_model(app_label, model_name):
        return apps.get_model(app_label, model_name) 
示例19
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

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

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

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

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__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 
示例20
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

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

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

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

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__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 
示例21
def _resolve_model(field, to):
    if "." in to:
        return apps.get_model(to)
    elif to == "self":
        return field.model
    else:
        return apps.get_model(field.model._meta.app_label, to) 
示例22
def tearDown(self):
        del apps.all_models['djangoseo']['dog'] 
示例23
def tearDown(self):
        del apps.all_models['djangoseo']['animal'] 
示例24
def init_django(self):
        try:
            import django

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
            django.setup()
            from django.apps import apps

            self.django_apps = apps
            self.django_initialized = True
        except BaseException:
            log.exception("Failed to initialize django") 
示例25
def setUp(self):
        apps.clear_cache() 
示例26
def test_clear_cache_clears_relation_tree(self):
        # The apps.clear_cache is setUp() should have deleted all trees.
        # Exclude abstract models that are not included in the Apps registry
        # and have no cache.
        all_models_with_cache = (m for m in self.all_models if not m._meta.abstract)
        for m in all_models_with_cache:
            self.assertNotIn('_relation_tree', m._meta.__dict__) 
示例27
def get_installed():
    ignore_apps = ['crispy_forms']
    return [app_config.name for app_config in apps.get_app_configs() if app_config.name not in ignore_apps] 
示例28
def init_django(self):
        try:
            import django

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
            django.setup()
            from django.apps import apps

            self.django_apps = apps
            self.django_initialized = True
        except BaseException:
            log.exception("Failed to initialize django") 
示例29
def _django_setup():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rssant.settings')
    if not apps.ready and not settings.configured:
        django.setup() 
示例30
def check_debug():
    """Check that Django's template debugging is enabled.

    Django's built-in "template debugging" records information the plugin needs
    to do its work.  Check that the setting is correct, and raise an exception
    if it is not.

    Returns True if the debug check was performed, False otherwise
    """
    from django.conf import settings

    if not settings.configured:
        return False

    # I _think_ this check is all that's needed and the 3 "hasattr" checks
    # below can be removed, but it's not clear how to verify that
    from django.apps import apps
    if not apps.ready:
        return False

    # django.template.backends.django gets loaded lazily, so return false
    # until they've been loaded
    if not hasattr(django.template, "backends"):
        return False
    if not hasattr(django.template.backends, "django"):
        return False
    if not hasattr(django.template.backends.django, "DjangoTemplates"):
        raise DjangoTemplatePluginException("Can't use non-Django templates.")

    for engine in django.template.engines.all():
        if not isinstance(engine, django.template.backends.django.DjangoTemplates):
            raise DjangoTemplatePluginException(
                "Can't use non-Django templates."
            )
        if not engine.engine.debug:
            raise DjangoTemplatePluginException(
                "Template debugging must be enabled in settings."
            )

    return True