Python django.conf.settings.configure() Examples

The following are 30 code examples for showing how to use django.conf.settings.configure(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: django-classified   Author: slyapustin   File: quicktest.py    License: MIT License 6 votes vote down vote up
def _tests(self):
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(self.DIRNAME, 'database.db'),
                }
            },
            INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
            MIDDLEWARE=self.MIDDLEWARE,
            ROOT_URLCONF='django_classified.tests.urls',
            STATIC_URL='/static/',
            TEMPLATES=self.TEMPLATES,
            SITE_ID=1
        )

        from django.test.runner import DiscoverRunner
        test_runner = DiscoverRunner()
        django.setup()

        failures = test_runner.run_tests(self.apps)
        if failures:
            sys.exit(failures) 
Example 2
Project: pinax-documents   Author: pinax   File: runtests.py    License: MIT License 6 votes vote down vote up
def runtests(*test_args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    # Compatibility with Django 1.7's stricter initialization
    if hasattr(django, "setup"):
        django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        test_args = ["pinax.documents.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ["tests"]

    failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example 3
Project: django-seed   Author: Brobin   File: runtests.py    License: MIT License 6 votes vote down vote up
def configure():
    from faker import Faker
    fake = Faker()

    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=(
            'django_seed',
            'django_nose',
        ),
        TEST_RUNNER = 'django_nose.NoseTestSuiteRunner',
        NOSE_ARGS = [
            '--with-coverage',
            '--cover-package=django_seed',
        ],
        SITE_ID=1,
        SECRET_KEY=fake.sha1(),
    ) 
Example 4
Project: pwned-passwords-django   Author: ubernostrum   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)

    # Then, call django.setup() to initialize the application registry
    # and other bits:
    import django

    django.setup()

    # Now we instantiate a test runner...
    from django.test.utils import get_runner

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 5
Project: django-sudo   Author: mattrobenolt   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure(config):
    from django.conf import settings

    settings.configure(
        AUTHENTICATION_BACKENDS=[
            "tests.base.FooPasswordBackend",
            "tests.base.StubPasswordBackend",
        ],
        DEBUG=True,
        DATABASE_ENGINE="sqlite3",
        DATABASES={
            "default": {
                "NAME": ":memory:",
                "ENGINE": "django.db.backends.sqlite3",
                "TEST_NAME": ":memory:",
            },
        },
        DATABASE_NAME=":memory:",
        TEST_DATABASE_NAME=":memory:",
        INSTALLED_APPS=INSTALLED_APPS,
        MIDDLEWARE_CLASSES=MIDDLEWARE_CLASSES,
        PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"],
        ROOT_URLCONF="tests.urls",
    ) 
Example 6
Project: django-ftpserver   Author: tokibito   File: conf.py    License: 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 7
Project: django-webdav-storage   Author: marazmiki   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    WEBDAV_URL = os.getenv('WEBDAV_URL', 'http://127.0.0.1:8080/')
    WEBDAV_PUBLIC_URL = os.getenv('WEBDAV_PUBLIC_URL',
                                  'http://127.0.0.1:8080/')
    WEBDAV_LISTING_BACKEND = os.getenv('WEBDAV_LISTING_BACKEND')

    settings.configure(
        INSTALLED_APPS=['django_webdav_storage'],
        MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'],
        MIDDLEWARES=['django.middleware.common.CommonMiddleware'],
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':MEMORY:'
            }
        },
        WEBDAV_URL=WEBDAV_URL,
        WEBDAV_PUBLIC_URL=WEBDAV_PUBLIC_URL,
        WEBDAV_RECURSIVE_MKCOL=True,
        WEBDAV_LISTING_BACKEND=WEBDAV_LISTING_BACKEND
    ) 
Example 8
Project: pinax-forums   Author: pinax   File: runtests.py    License: MIT License 6 votes vote down vote up
def runtests(*test_args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        if not test_args:
            test_args = ["pinax.forums.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ["tests"]

    failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example 9
def run_tests():
    # First configure settings, then call django.setup() to initialise
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)
    import django

    django.setup()

    # Now create the test runner
    from django.test.utils import get_runner

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 10
Project: propublica-congress   Author: eyeseast   File: test.py    License: MIT License 6 votes vote down vote up
def test_django_cache(self):
        try:
            from django.conf import settings
            settings.configure(CACHE_BACKEND = 'locmem://')
            from django.core.cache import cache
        except ImportError:
            # no Django, so nothing to test
            return
        
        congress = Congress(API_KEY, cache)
        
        self.assertEqual(congress.http.cache, cache)
        self.assertEqual(congress.members.http.cache, cache)
        self.assertEqual(congress.bills.http.cache, cache)
        self.assertEqual(congress.votes.http.cache, cache)
        
        try:
            bills = congress.bills.introduced('house')
        except Exception as e:
            self.fail(e) 
Example 11
Project: django-spillway   Author: bkg   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def runtests():
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)
    django.setup()
    from spillway.models import upload_to
    os.mkdir(os.path.join(TMPDIR, upload_to.path))
    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)
    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
    try:
        status = runner_class(
            verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
    except Exception:
        traceback.print_exc()
        status = 1
    finally:
        teardown()
    sys.exit(status) 
Example 12
Project: django-taggit-labels   Author: bennylope   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3"}
        },
        INSTALLED_APPS=[
            "django.contrib.auth",
            "django.contrib.contenttypes",
            # "django.contrib.sites",
            "taggit",
            "taggit_labels",
            "test_app",
        ],
        MIDDLEWARE_CLASSES=(),
        SITE_ID=1,
    )
    try:
        django.setup()
    except AttributeError:
        # Django 1.7 or lower
        pass 
Example 13
def configure():
    from django.conf import settings

    settings.configure(
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': ':memory:'}},
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',

            'rest_framework',
            'tests',
        ),
    )

    import django
    django.setup() 
Example 14
Project: django-rest-framework-simplejwt   Author: SimpleJWT   File: conf.py    License: MIT License 6 votes vote down vote up
def django_configure():
    from django.conf import settings

    settings.configure(
        INSTALLED_APPS=(
            'django.contrib.admin',
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',

            'rest_framework',
            'rest_framework_simplejwt',
            'rest_framework_simplejwt.token_blacklist',
        ),
    )

    try:
        import django
        django.setup()
    except AttributeError:
        pass 
Example 15
Project: django_coverage_plugin   Author: nedbat   File: plugin.py    License: Apache License 2.0 6 votes vote down vote up
def read_template_source(filename):
    """Read the source of a Django template, returning the Unicode text."""
    # Import this late to be sure we don't trigger settings machinery too
    # early.
    from django.conf import settings

    if not settings.configured:
        settings.configure()

    with open(filename, "rb") as f:
        # The FILE_CHARSET setting will be removed in 3.1:
        # https://docs.djangoproject.com/en/3.0/ref/settings/#file-charset
        if django.VERSION >= (3, 1):
            charset = 'utf-8'
        else:
            charset = settings.FILE_CHARSET
        text = f.read().decode(charset)

    return text 
Example 16
Project: django-cognito-jwt   Author: labd   File: conftest.py    License: MIT License 6 votes vote down vote up
def pytest_configure():
    settings.configure(
        COGNITO_AWS_REGION="eu-central-1",
        COGNITO_USER_POOL="bla",
        COGNITO_AUDIENCE="my-client-id",
        INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes"],
        MIDDLEWARE_CLASSES=[],
        CACHES={
            "default": {
                "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
                "LOCATION": "unique-snowflake",
            }
        },
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite"}
        },
        ROOT_URLCONF="urls",
    ) 
Example 17
Project: django-websocket-request   Author: GetBlimp   File: run_tests.py    License: MIT License 6 votes vote down vote up
def main():
    settings.configure(
        ROOT_URLCONF='wsrequest.tests',
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
        ],
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME':  'db.sqlite3',
            }
        }
    )

    from django.test.utils import get_runner

    test_runner = get_runner(settings)(verbosity=1, interactive=True)

    failures = test_runner.run_tests(['wsrequest.tests'])

    sys.exit(failures) 
Example 18
Project: django-session-timeout   Author: labd   File: conftest.py    License: MIT License 6 votes vote down vote up
def pytest_configure():
    settings.configure(
        INSTALLED_APPS=[
            "django.contrib.contenttypes",
            "django.contrib.auth",
            "django.contrib.sessions",
        ],
        MIDDLEWARE_CLASSES=[],
        ROOT_URLCONF="tests.urls",
        CACHES={
            "default": {
                "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
                "LOCATION": "unique-snowflake",
            }
        },
        SESSION_ENGINE="django.contrib.sessions.backends.cache",
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite"}
        },
    ) 
Example 19
Project: djangorestframework-expander   Author: silverlogic   File: conftest.py    License: MIT License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    settings.configure(
        ROOT_URLCONF='tests.project.urls',
        SECRET_KEY='not so secret',
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': 'db.sqlite',
            }
        },
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'rest_framework',
            'tests.project'
        ],
    ) 
Example 20
Project: django-elevate   Author: justinmayer   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure(config):
    from django.conf import settings

    settings.configure(
        AUTHENTICATION_BACKENDS=[
            'tests.base.FooPasswordBackend',
            'tests.base.StubPasswordBackend',
        ],
        DEBUG=True,
        DATABASE_ENGINE='sqlite3',
        DATABASES={
            'default': {
                'NAME': ':memory:',
                'ENGINE': 'django.db.backends.sqlite3',
                'TEST_NAME': ':memory:',
            },
        },
        DATABASE_NAME=':memory:',
        TEST_DATABASE_NAME=':memory:',
        INSTALLED_APPS=INSTALLED_APPS,
        MIDDLEWARE_CLASSES=MIDDLEWARE_CLASSES,
        PASSWORD_HASHERS=['django.contrib.auth.hashers.MD5PasswordHasher'],
        ROOT_URLCONF='tests.urls',
    ) 
Example 21
Project: django-rest-assured   Author: ydaniv   File: conftest.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def pytest_configure():
    settings.configure(
        ROOT_URLCONF='tests.urls',

        ALLOWED_HOSTS=['testserver'],

        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': 'test_db'
            }
        },

        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',

            'rest_framework',
            'tests',
        ]
    ) 
Example 22
Project: pinax-teams   Author: pinax   File: runtests.py    License: MIT License 6 votes vote down vote up
def runtests(*test_args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        test_args = ["pinax.teams.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ["tests"]

    failures = runner_class(
        verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example 23
Project: django-calaccess-campaign-browser   Author: california-civic-data-coalition   File: setup.py    License: MIT License 6 votes vote down vote up
def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={
                'default': {
                    'NAME': ':memory:',
                    'ENGINE': 'django.db.backends.sqlite3'
                }
            },
            INSTALLED_APPS=('calaccess_campaign_browser',),
            MIDDLEWARE_CLASSES=()
        )
        from django.core.management import call_command
        import django
        if django.VERSION[:2] >= (1, 7):
            django.setup()
        call_command('test', 'calaccess_campaign_browser') 
Example 24
Project: pinax-documents   Author: pinax   File: makemigrations.py    License: MIT License 5 votes vote down vote up
def run(*args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    django.core.management.call_command(
        "makemigrations",
        "documents",
        *args
    ) 
Example 25
Project: django-healthchecks   Author: mvantellingen   File: conftest.py    License: MIT License 5 votes vote down vote up
def pytest_configure():
    settings.configure(
        HEALTH_CHECKS={},
        MIDDLEWARE_CLASSES=[],
        INSTALLED_APPS=[
            'django.contrib.admin',
            'django.contrib.contenttypes',
            'django.contrib.auth',
            'django.contrib.sessions',
            'django_healthchecks',
        ],
        CACHES={
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                'LOCATION': 'unique-snowflake',
            }
        },
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': 'db.sqlite',
            },
        },
        MIDDLEWARE = (
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
        ),
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'OPTIONS': {
                    'loaders': (
                        'django.template.loaders.app_directories.Loader',
                    ),
                },
            },
        ],
        USE_TZ=True,
        ROOT_URLCONF='test_urls',
    ) 
Example 26
Project: django-phone-verify   Author: CuriousLearner   File: conftest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pytest_configure():
    from tests import test_settings

    settings.configure(**test_settings.DJANGO_SETTINGS)
    django.setup() 
Example 27
Project: django-angularjs-blog   Author: bluedazzle   File: test_Serializer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        self.time_func = TimeFormatFactory.get_time_func('string')
        # DATABASES = {
        #     'default': {
        #     'ENGINE': 'django.db.backends.sqlite3',
        #     'NAME': ':memory:',
        #     'USER': '',                      # Not used with sqlite3.
        #     'PASSWORD': '',                  # Not used with sqlite3.
        #     'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        #     'PORT': '',
        #     }
        # }
        # settings.configure(DATABASES=DATABASES, DEBUG=True)
        # class TestAuthor(models.Model):
        #     name = models.CharField(default='test_author')
        #
        #     def __unicode__(self):
        #         return self.name
        #
        # class TestTags(models.Model):
        #     tag = models.CharField(default='test_tag')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        # class TestArticle(models.Model):
        #     title = models.CharField(default='test')
        #     content = models.CharField(default='test')
        #     author = models.ForeignKey(TestAuthor, related_name='author_art')
        #     tags = models.ManyToManyField(TestTags, related_name='tag_art')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        #
        # self.author = TestAuthor()
        # self.author.save()
        # tags = TestTags(tag='tag1')
        # tags.save()
        # self.article = TestArticle(author=self.author)
        # self.article.tags.add(tags)
        # self.article.save() 
Example 28
Project: django-micro   Author: zenwalker   File: django_micro.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_app_label():
    if _app_config is None:
        raise ImproperlyConfigured(
            "Application label is not detected. "
            "Check whether the configure() was called.")
    return _app_config.label 
Example 29
Project: django-micro   Author: zenwalker   File: django_micro.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def configure(config_dict={}, django_admin=False):
    _create_app(inspect.stack())  # load application from parent module

    if 'BASE_DIR' in config_dict:
        config_dict.setdefault('TEMPLATE_DIRS', [os.path.join(config_dict['BASE_DIR'], 'templates')])

    if django_admin:
        _configure_admin(config_dict)

    django_config = {
        'INSTALLED_APPS': ['django_micro._app_config'] + config_dict.pop('INSTALLED_APPS', []),
        'ROOT_URLCONF': __name__,
        'TEMPLATES': [{
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': config_dict.pop('TEMPLATE_DIRS', []),
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': config_dict.pop('CONTEXT_PROCESSORS', []),
                'builtins': [__name__],
            },
        }],
    }

    django_config.update({key: val for key, val in config_dict.items() if key.isupper()})
    settings.configure(**django_config)
    django.setup() 
Example 30
Project: django-micro   Author: zenwalker   File: django_micro.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run():
    if not settings.configured:
        raise ImproperlyConfigured("You should call configure() after configuration define.")

    if _parent_module.__name__ == '__main__':
        from django.core.management import execute_from_command_line
        execute_from_command_line(sys.argv)
    else:
        from django.core.wsgi import get_wsgi_application
        return get_wsgi_application()