Python django.conf.settings.configured() Examples

The following are 30 code examples of django.conf.settings.configured(). 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.conf.settings , or try the search function .
Example #1
Source File: runtests.py    From pinax-documents with 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 #2
Source File: runtests.py    From libreborme with GNU Affero General Public License v3.0 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 = ["borme.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        if not test_args:
            test_args = ["tests"]

    failures = runner_class(verbosity=1,
                            interactive=True,
                            failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example #3
Source File: utils.py    From uwsgi_tasks with MIT License 6 votes vote down vote up
def django_setup(settings_module=None):
    """Initialize Django if required, must be run before performing
    any task on spooler or mule.
    """
    from django.conf import settings, ENVIRONMENT_VARIABLE

    if settings.configured:
        return

    if settings_module:
        import os
        os.environ[ENVIRONMENT_VARIABLE] = settings_module

    try:
        # django > 1.7
        from django import setup
    except ImportError:
        # django < 1.7
        def setup():
            settings._setup()

    setup() 
Example #4
Source File: runtests.py    From pinax-wiki with 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.wiki.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 #5
Source File: runtests.py    From pinax-teams with 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 #6
Source File: plugin.py    From django_coverage_plugin with 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 #7
Source File: runtests.py    From django-spillway with 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 #8
Source File: runtests.py    From pinax-forums with 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
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 #10
Source File: test_django.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def django_settings(self):
        import django
        from django.conf import settings
        from django.contrib import admin
        from django.urls import path

        if settings.configured:
            return

        settings.configure(
            ALLOWED_HOSTS=[
                'testserver',
            ],
            INSTALLED_APPS=[
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.messages',
                'django.contrib.sessions',
            ],
            MIDDLEWARE=[
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
            ]
        )
        django.setup()
        settings.ROOT_URLCONF = (
            path('admin/', admin.site.urls),
        ) 
Example #11
Source File: makemigrations.py    From pinax-documents with 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 #12
Source File: context.py    From django-stubs with MIT License 5 votes vote down vote up
def initialize_django(settings_module: str) -> Tuple['Apps', 'LazySettings']:
    with temp_environ():
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module

        # add current directory to sys.path
        sys.path.append(os.getcwd())

        def noop_class_getitem(cls, key):
            return cls

        from django.db import models

        models.QuerySet.__class_getitem__ = classmethod(noop_class_getitem)  # type: ignore
        models.Manager.__class_getitem__ = classmethod(noop_class_getitem)  # type: ignore

        from django.conf import settings
        from django.apps import apps

        apps.get_models.cache_clear()  # type: ignore
        apps.get_swappable_settings_name.cache_clear()  # type: ignore

        if not settings.configured:
            settings._setup()

        apps.populate(settings.INSTALLED_APPS)

    assert apps.apps_ready
    assert settings.configured

    return apps, settings 
Example #13
Source File: django_micro.py    From django-micro with 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() 
Example #14
Source File: makemigrations.py    From pinax-wiki with 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",
        "pinax_wiki",
        *args
    ) 
Example #15
Source File: conftest.py    From django-jwt-auth with MIT License 5 votes vote down vote up
def pytest_configure():
    if not settings.configured:
        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'

    try:
        django.setup()
    except AttributeError:
        pass 
Example #16
Source File: test_django_middleware.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        from django.conf import settings as django_settings
        from django.test.utils import setup_test_environment

        if not django_settings.configured:
            django_settings.configure()
        setup_test_environment() 
Example #17
Source File: test_django_db_middleware.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        from django.conf import settings as django_settings
        from django.test.utils import setup_test_environment

        if not django_settings.configured:
            django_settings.configure()
        setup_test_environment() 
Example #18
Source File: conftest.py    From django-heythere with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pytest_configure():
    if not settings.configured:
        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 
Example #19
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #20
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def file_tracer(self, filename):
        if filename.startswith(self.django_template_dir):
            if not self.debug_checked:
                # Keep calling check_debug until it returns True, which it
                # will only do after settings have been configured
                self.debug_checked = check_debug()

            return self
        return None 
Example #21
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def main_help_text(self, commands_only=False):
        """
        Returns the script's main help text, as a string.
        """
        if commands_only:
            usage = sorted(get_commands().keys())
        else:
            usage = [
                "",
                "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
                "",
                "Available subcommands:",
            ]
            commands_dict = collections.defaultdict(lambda: [])
            for name, app in six.iteritems(get_commands()):
                if app == 'django.core':
                    app = 'django'
                else:
                    app = app.rpartition('.')[-1]
                commands_dict[app].append(name)
            style = color_style()
            for app in sorted(commands_dict.keys()):
                usage.append("")
                usage.append(style.NOTICE("[%s]" % app))
                for name in sorted(commands_dict[app]):
                    usage.append("    %s" % name)
            # Output an extra note if settings are not properly configured
            if self.settings_exception is not None:
                usage.append(style.NOTICE(
                    "Note that only Django core commands are listed "
                    "as settings are not properly configured (error: %s)."
                    % self.settings_exception))

        return '\n'.join(usage) 
Example #22
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 #23
Source File: setup.py    From django-peeringdb with Apache License 2.0 5 votes vote down vote up
def configure(**kwargs):
    if settings.configured:
        return

    defaults = _Settings()
    defaults.update(global_settings)
    defaults.update(default_settings)
    settings.configure(default_settings=defaults, **kwargs)
    setup() 
Example #24
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 #25
Source File: makemigrations.py    From pinax-forums with 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",
        "pinax_forums",
        *args
    ) 
Example #26
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def main_help_text(self, commands_only=False):
        """Return the script's main help text, as a string."""
        if commands_only:
            usage = sorted(get_commands())
        else:
            usage = [
                "",
                "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
                "",
                "Available subcommands:",
            ]
            commands_dict = defaultdict(lambda: [])
            for name, app in get_commands().items():
                if app == 'django.core':
                    app = 'django'
                else:
                    app = app.rpartition('.')[-1]
                commands_dict[app].append(name)
            style = color_style()
            for app in sorted(commands_dict):
                usage.append("")
                usage.append(style.NOTICE("[%s]" % app))
                for name in sorted(commands_dict[app]):
                    usage.append("    %s" % name)
            # Output an extra note if settings are not properly configured
            if self.settings_exception is not None:
                usage.append(style.NOTICE(
                    "Note that only Django core commands are listed "
                    "as settings are not properly configured (error: %s)."
                    % self.settings_exception))

        return '\n'.join(usage) 
Example #27
Source File: conftest.py    From django-klingon with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pytest_configure():
    from django.conf import settings
    if not settings.configured:
        settings.configure(
            DEBUG_PROPAGATE_EXCEPTIONS=True,
            DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                       'NAME': ':memory:'}},
            INSTALLED_APPS=(
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.admin',
                'autoslug',
                'klingon',
                'tests',
                'tests.testapp',
            ),
            SITE_ID=1,
            SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
            LANGUAGES = (
                ('en', 'English'),
                ('pt_br', 'Brazilian Portuguese'),
                ('es', 'Spanish'),
            ),
            MIDDLEWARE_CLASSES=(),
        )

        try:
            import django
            django.setup()
        except AttributeError:
            pass 
Example #28
Source File: makemessages.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def main():
    if not settings.configured:
        module_root = path.dirname(path.realpath(__file__))

        settings.configure(
            DEBUG=False,
            INSTALLED_APPS=(
                'private_storage',
            ),
        )

    django.setup()
    makemessages() 
Example #29
Source File: test_request_normalization.py    From flex with MIT License 5 votes vote down vote up
def test_django_request_normalization(httpbin):
    from django.conf import settings
    if not settings.configured:
        settings.configure()
        settings.ALLOWED_HOSTS.append('127.0.0.1')

    import django.http.request

    url = urlparse.urlparse(httpbin.url + '/get')

    raw_request = django.http.request.HttpRequest()
    raw_request.method = 'GET'
    raw_request.path = url.path
    raw_request._body = None
    raw_request.META = {'CONTENT_TYPE': 'application/json', 'HTTP_HOST': url.netloc, 'QUERY_STRING': 'key=val'}

    request = normalize_request(raw_request)

    assert request.path == '/get'
    assert request.content_type == 'application/json'
    assert request.url == httpbin.url + '/get?key=val'
    assert request.method == 'get'

    del raw_request.META['CONTENT_TYPE']
    request = normalize_request(raw_request)
    assert request.content_type is None 
Example #30
Source File: test_response_normalization.py    From flex with MIT License 5 votes vote down vote up
def test_django_response_normalization(httpbin):
    from django.conf import settings
    if not settings.configured:
        settings.configure()
        settings.ALLOWED_HOSTS.append('127.0.0.1')

    import django.http.request
    import django.http.response

    url = urlparse.urlparse(httpbin.url + '/get')

    raw_request = django.http.request.HttpRequest()
    raw_request.method = 'GET'
    raw_request.path = url.path
    raw_request._body = None
    raw_request.META = {'CONTENT_TYPE': 'application/json', 'HTTP_HOST': url.netloc, 'QUERY_STRING': 'key=val'}

    raw_response = django.http.response.HttpResponse(b'', content_type='application/json', status=200)

    response = normalize_response(raw_response, raw_request)

    assert response.path == '/get'
    assert response.content_type == 'application/json'
    assert response.url == httpbin.url + '/get?key=val'
    assert response.status_code == '200'

    del raw_response._headers['content-type']

    response = normalize_response(raw_response, raw_request)
    assert response.content_type is None

    redirect_url = 'http://www.example.org'
    raw_response = django.http.response.HttpResponseRedirect(redirect_url)

    response = normalize_response(raw_response)

    assert response.url == redirect_url