Python django.conf.settings.configured() Examples

The following are 30 code examples for showing how to use django.conf.settings.configured(). 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: 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 2
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 3
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 4
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 5
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 6
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 7
Project: pinax-wiki   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.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 8
Project: uwsgi_tasks   Author: Bahus   File: utils.py    License: 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 9
Project: libreborme   Author: PabloCastellano   File: runtests.py    License: 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 10
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 11
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() 
Example 12
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 13
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: 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 14
Project: DeerU   Author: gojuukaze   File: __init__.py    License: 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 15
Project: DeerU   Author: gojuukaze   File: __init__.py    License: 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 16
Project: DeerU   Author: gojuukaze   File: __init__.py    License: 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 17
Project: DeerU   Author: gojuukaze   File: __init__.py    License: 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 18
Project: django-klingon   Author: angvp   File: conftest.py    License: 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 19
Project: django-private-storage   Author: edoburu   File: makemessages.py    License: 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 20
Project: flex   Author: pipermerriam   File: test_request_normalization.py    License: 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 21
Project: flex   Author: pipermerriam   File: test_response_normalization.py    License: 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 
Example 22
Project: django-ethereum-events   Author: artemistomaras   File: runtests.py    License: MIT License 5 votes vote down vote up
def runtests():
    settings_file = 'django_ethereum_events.settings.test'
    if not settings.configured:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_file)

    django.setup()

    from django.test.runner import DiscoverRunner
    runner_class = DiscoverRunner
    test_args = ['django_ethereum_events']

    failures = runner_class(
        verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example 23
Project: pinax-forums   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",
        "pinax_forums",
        *args
    ) 
Example 24
Project: django-rdkit   Author: rdkit   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def runtests():
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    django.setup()

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

    sys.exit(call_command('test', 'tests')) 
Example 25
Project: django-cloud-deploy   Author: GoogleCloudPlatform   File: storage.py    License: Apache License 2.0 5 votes vote down vote up
def collect_static_content(self):
        """Collect static content of the provided Django project.

        This function should be called only after django.setup() is called.

        Raises:
            CloudStorageError: If Django environment is not correctly
                setup.
        """

        if not settings.configured:
            raise CloudStorageError(
                'Django environment is not setup correctly or the settings '
                'module is invalid. We cannot collect static files.')
        cwd = os.getcwd()
        # Change directory to the Django project directory. If we do not do
        # this, static content will be collected in your current directory.
        # This is not expected.
        os.chdir(settings.BASE_DIR)
        try:
            management.call_command('collectstatic',
                                    verbosity=0,
                                    interactive=False)
        except Exception as e:
            raise crash_handling.UserError(
                'Not able to collect static files.') from e
        finally:
            os.chdir(cwd) 
Example 26
Project: rssant   Author: anyant   File: django_setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _django_setup():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rssant.settings')
    if not apps.ready and not settings.configured:
        django.setup() 
Example 27
Project: janeway   Author: BirkbeckCTP   File: __init__.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def load_janeway_settings():

    with LOCK:
        if settings.configured:
            return

        settings_module = os.environ["JANEWAY_SETTINGS_MODULE"]
        janeway_settings = {
            k: v for k, v in janeway_global_settings.__dict__.items()
            if k.isupper()
        }
        if os.environ["JANEWAY_SETTINGS_MODULE"] != "core.janeway_global_settings":
            custom_module = importlib.import_module(os.environ["JANEWAY_SETTINGS_MODULE"])
            custom_settings = {
                k: v for k, v in custom_module.__dict__.items()
                if k.isupper()
            }
            logging.info(
                "Loading settings from %s" % (
                    os.environ["JANEWAY_SETTINGS_MODULE"],
            ))
            logging.debug(
                    "Loading the following custom settings: %s" %(
                    custom_settings.keys(),
            ))
            for k, v in custom_settings.items():
                if k in MERGEABLE_SETTINGS:
                    janeway_settings[k] = merge_settings(janeway_settings[k], v)
                else:
                    janeway_settings[k] = v

        settings.configure(**janeway_settings) 
Example 28
Project: zing   Author: evernote   File: conftest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pytest_configure():
    if not settings.configured:
        from pootle import syspath_override  # Needed for monkey-patching

        syspath_override
        os.environ["DJANGO_SETTINGS_MODULE"] = "pootle.settings"
        os.environ["ZING_SETTINGS"] = os.path.join(WORKING_DIR, "settings.py")
        # The call to `setup()` was needed before a fix for
        # pytest-dev/pytest-django#146 was available. This happened in version
        # 2.9; unfortunately upgrading to 2.9+ is not possible yet because a fix
        # for pytest-dev/pytest-django#289 is needed too, and this is not part
        # of any releases for the time being.
        setup() 
Example 29
Project: openapi-core   Author: p1c2u   File: test_django.py    License: 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 30
Project: django-peeringdb   Author: peeringdb   File: setup.py    License: 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()