Python django.apps() Examples

The following are 30 code examples of django.apps(). 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 , or try the search function .
Example #1
Source File: mocks.py    From django-mock-queries with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: test_migration.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
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",
            ]
        ) 
Example #4
Source File: test_django.py    From scout_apm_python with MIT License 6 votes vote down vote up
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",
            ]
        ) 
Example #5
Source File: runtests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: runtests.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: runtests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: conf.py    From django-ftpserver with MIT License 6 votes vote down vote up
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() 
Example #9
Source File: setup_tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: runtests.py    From django-sqlserver with MIT License 6 votes vote down vote up
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 
Example #11
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 #12
Source File: tests.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #13
Source File: abstract.py    From django-crudbuilder with Apache License 2.0 5 votes vote down vote up
def get_model_class(self):
        """Returns model class"""
        try:
            c = ContentType.objects.get(app_label=self.app, model=self.model)
        except ContentType.DoesNotExist:
            # try another kind of resolution
            # fixes a situation where a proxy model is defined in some external app.
            if django.VERSION >= (1, 7):
                return apps.get_model(self.app, self.model)
        else:
            return c.model_class() 
Example #14
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: runtests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def get_installed():
    return [app_config.name for app_config in apps.get_app_configs()] 
Example #16
Source File: grpc_server.py    From xos with Apache License 2.0 5 votes vote down vote up
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") 
Example #17
Source File: setup_tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_installed():
    return [app_config.name for app_config in apps.get_app_configs()] 
Example #18
Source File: runtests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_installed():
    return [app_config.name for app_config in apps.get_app_configs()] 
Example #19
Source File: image_processors.py    From dvhb-hybrid with MIT License 5 votes vote down vote up
def resize(self, image_name, w, h, processor='size'):
        django.setup()
        Image = apps.get_model('files.Image')
        image = Image(image=image_name)
        self._get_image(image.image, w, h, processor=processor) 
Example #20
Source File: test_migration.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_migrate_to_form_question_natural_key_forward(transactional_db):
    executor = MigrationExecutor(connection)
    app = "caluma_form"
    migrate_from = [(app, "0023_auto_20190729_1448")]
    migrate_to = [(app, "0024_auto_20190919_1244")]

    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")
    form_question = FormQuestion.objects.create(form=form_1, question=question_1)

    assert isinstance(form_question.pk, UUID)

    # Migrate forwards.
    executor.loader.build_graph()  # reload.
    executor.migrate(migrate_to)
    new_apps = executor.loader.project_state(migrate_to).apps

    # Test the new data.
    FormQuestion = new_apps.get_model(app, "FormQuestion")

    form_question = FormQuestion.objects.first()

    assert form_question.pk == "form-1.question-1" 
Example #21
Source File: test_migration.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def _verify_foreign_key_types(apps):

    for models in apps.all_models.values():
        for model in models.values():
            slug_fks = [
                field
                for field in model._meta.fields
                if field.is_relation and field.target_field.name == "slug"
            ]

            for field in slug_fks:
                # ok we have a slug foreign key
                fk_params = field.db_parameters(connection)
                target_params = field.target_field.db_parameters(connection)

                # verify django-internal specified type
                assert (
                    fk_params["type"] == target_params["type"]
                ), f"Foreign key field {field}: type mismatch with destination in django-internal representation"

                # check if the DB agrees
                fk_dbtype = col_type_from_db(field, connection)
                target_dbtype = col_type_from_db(field.target_field, connection)
                assert (
                    fk_dbtype == target_dbtype
                ), f"Foreign key field {field}: type mismatch with destination in DB" 
Example #22
Source File: test_migration.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_slugfield_length_correctness(transactional_db):
    """Detect deviation of foreign key types from target field types.

    Note: If this test fails, you'll most likely need to create a new
    migration and run caluma.utils.fix_foreign_key_types() in it to
    cleanup the mess again.
    """

    # Just make sure we're at the newest version, as we're messing
    # with migrations in these tests around here
    call_command("migrate", no_input=True)
    _verify_foreign_key_types(django.apps.apps) 
Example #23
Source File: docstrings.py    From sphinxcontrib-django with Apache License 2.0 5 votes vote down vote up
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) 
Example #24
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #25
Source File: test_fields.py    From django-osm-field with MIT License 5 votes vote down vote up
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() 
Example #26
Source File: test_fields.py    From django-osm-field with MIT License 5 votes vote down vote up
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() 
Example #27
Source File: compat.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_installed(appname):
        return appname in settings.INSTALLED_APPS #or apps.is_installed(appname) 
Example #28
Source File: compat.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_django_model(app_label, model_name):
        return apps.get_model(app_label, model_name) 
Example #29
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
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