django.conf - python examples

Here are the examples of the python api django.conf taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

3 View Complete Implementation : application_django.py
Copyright MIT License
Author : WolframResearch
    def setUp(self):

        from django.conf import settings

        settings.configure(
            ROOT_URLCONF="wolframwebengine.examples.djangoapp.urls",
            ALLOWED_HOSTS="*",
            DEBUG=True,
        )

        import django

        django.setup()

        from wolframwebengine.examples.djangoapp.urls import session

        self.session = session
        self.client = Client()

3 View Complete Implementation : migrate.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : kogan
def migrate(name):
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)
    import django

    django.setup()

    from django.core import management

    management.call_command("makemigrations", "subscriptions", name=name)

3 View Complete Implementation : runner.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mattiaslinnap
def main(args):
    # Since this test suite is designed to be ran outside of ./manage.py test, we need to do some setup first.
    import django
    from django.conf import settings
    settings.configure(INSTALLED_APPS=['testapp'], DATABASES=DATABASES_FOR_DB[args.db], DB_NAME=args.db)
    django.setup()

    from django.test.runner import DiscoverRunner
    test_runner = DiscoverRunner(top_level=TESTS_DIR, interactive=False, keepdb=False)
    if args.testpaths:
        paths = ['tests.' + p for p in args.testpaths]
        failures = test_runner.run_tests(paths)
    else:
        failures = test_runner.run_tests(['tests'])
    if failures:
        sys.exit(1)

3 View Complete Implementation : setup.py
Copyright MIT License
Author : datadesk
    def run(self):
        import django
        from django.conf import settings
        from django.core.management import call_command
        settings.configure(
            DATABASES={
                'default': {
                    'NAME': 'test',
                    'USER': 'postgres',
                    'ENGINE': 'django.contrib.gis.db.backends.postgis'
                },
            },
            MEDIA_ROOT="media",
            INSTALLED_APPS=("anss",),
        )
        django.setup()
        call_command('test', 'anss')

3 View Complete Implementation : cli.py
Copyright MIT License
Author : learningequality
def _migrate_databases():
    """
    Try to migrate all active databases. This should not be called unless Django has
    been initialized.
    """
    from django.conf import settings

    for database in settings.DATABASES:
        call_command("migrate", interactive=False, database=database)

    # load morango fixtures needed for certificate related operations
    call_command("loaddata", "scopedefinitions")

3 View Complete Implementation : basehttp.py
Copyright GNU General Public License v2.0
Author : blackye
    def __init__(self, *args, **kwargs):
        from django.conf import settings
        self.admin_static_prefix = urljoin(settings.STATIC_URL, 'admin/')
        # We set self.path to avoid crashes in log_message() on unsupported
        # requests (like "OPTIONS").
        self.path = ''
        self.style = color_style()
        super(WSGIRequestHandler, self).__init__(*args, **kwargs)

3 View Complete Implementation : setup.py
Copyright MIT License
Author : ivelum
    def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={'default': {
                'NAME': ':memory:',
                'ENGINE': 'django.db.backends.sqlite3'}
            },
            INSTALLED_APPS=('django_uidfield', 'django.contrib.contenttypes')
        )
        from django.core.management import call_command
        import django

        django.setup()

        call_command('test', 'django_uidfield')

3 View Complete Implementation : setup.py
Copyright MIT License
Author : naritotakizawa
    def run_tests(self):
        #import here, cause outside the eggs aren't loaded
        import django
        from django.conf import settings
        from django.test.utils import get_runner
        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
        django.setup()
        TestRunner = get_runner(settings)
        test_runner = TestRunner()
        failures = test_runner.run_tests(['tests'])
        sys.exit(bool(failures))

3 View Complete Implementation : runtests.py
Copyright MIT License
Author : xuchaoa
def django_tests(verbosity, interactive, failfast, test_labels):
    from django.conf import settings
    state = setup(verbosity, test_labels)
    extra_tests = []

    # Run the test suite, including the extra validation tests.
    from django.test.utils import get_runner
    if not hasattr(settings, 'TEST_RUNNER'):
        settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
    TestRunner = get_runner(settings)

    test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
        failfast=failfast)
    failures = test_runner.run_tests(test_labels or get_test_modules(), extra_tests=extra_tests)

    teardown(state)
    return failures

3 View Complete Implementation : serve_django_app.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dw
def serve_django_app(settings_name):
    os.listdir = lambda path: []

    os.environ['DJANGO_SETTINGS_MODULE'] = settings_name
    import django
    args = ['manage.py', 'runserver', '0:9191', '--noreload']
    from django.conf import settings
    #settings.configure()
    django.setup()
    from django.core.management.commands import runserver
    runserver.Command().run_from_argv(args)

3 View Complete Implementation : runtests.py
Copyright MIT License
Author : ex-ut
def runtests():
    import django
    from django.conf import settings
    from django.test.utils import get_runner

    if hasattr(django, 'setup'):
        django.setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(['tests'])
    sys.exit(bool(failures))

3 View Complete Implementation : plugin.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _configurePservSettings(self):
        # Configure the provisioningserver settings based on the Django
        # django settings.
        from django.conf import settings as django_settings
        from provisioningserver import settings

        settings.DEBUG = django_settings.DEBUG

3 View Complete Implementation : runtests.py
Copyright MIT License
Author : xuchaoa
def teardown(state):
    from django.conf import settings
    # Removing the temporary TEMP_DIR. Ensure we past in unicode
    # so that it will successfully remove temp trees containing
    # non-ASCII filenames on Windows. (We're astuming the temp dir
    # name itself does not contain non-ASCII characters.)
    shutil.rmtree(smart_text(TEMP_DIR))
    # Restore the old settings.
    for key, value in state.items():
        setattr(settings, key, value)

3 View Complete Implementation : runtests.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : kogan
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)

3 View Complete Implementation : test_django.py
Copyright MIT License
Author : kiwicom
def test_settings_access():
    """When `setting` are accessed in this way after patching."""
    # Explicit import to check how custom __getattribute__ is working
    from django.conf import settings

    astert settings.SECRET == "value"

3 View Complete Implementation : migraterunner.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mattiaslinnap
def main(args):
    try:
        create_database(args)

        # Since this test suite is designed to be ran outside of ./manage.py test, we need to do some setup first.
        import django
        from django.conf import settings
        settings.configure(INSTALLED_APPS=['testmigrationsapp'], DATABASES=DATABASES_FOR_DB[args.db])
        django.setup()

        management.call_command('migrate', 'testmigrationsapp', verbosity=1)

        import django.db
        django.db.connections.close_all()
    finally:
        destroy_database(args)

3 View Complete Implementation : conftest.py
Copyright BSD 2-Clause "Simplified" License
Author : kezabelle
def pytest_configure():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
    import django
    from django.conf import settings
    if settings.configured and hasattr(django, 'setup'):
        django.setup()

3 View Complete Implementation : registry.py
Copyright MIT License
Author : fgmacedo
def _autodiscover_modules(module_name):  # pragma: no cover
    "Django 1.6 compat to provide `autodiscover_modules`"
    from django.conf import settings
    from django.utils.importlib import import_module

    for app in settings.INSTALLED_APPS:
        # Attempt to import the app's `module_name`.
        try:
            import_module('{app}.{module}'.format(app=app, module=module_name))
        except Exception:
            past

3 View Complete Implementation : test_django_db_middleware.py
Copyright Apache License 2.0
Author : census-instrumentation
    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()

3 View Complete Implementation : test_utils.py
Copyright Apache License 2.0
Author : criteo
def prepare_graphite():
    """Make sure that we have a working Graphite environment."""
    # Setup sys.path
    prepare_graphite_imports()
    os.environ["DJANGO_SETTINGS_MODULE"] = "graphite.settings"

    # Redirect logs somewhere writable
    from django.conf import settings

    settings.LOG_DIR = tempfile.gettempdir()

    # Setup Django
    import django

    django.setup()

3 View Complete Implementation : makemigrationsrunner.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : mattiaslinnap
def main(args):
    # Since this test suite is designed to be ran outside of ./manage.py test, we need to do some setup first.
    import django
    from django.conf import settings
    settings.configure(INSTALLED_APPS=['testmigrationsapp'], DATABASES=DATABASES)
    django.setup()
    management.call_command('makemigrations', 'testmigrationsapp', verbosity=0)

0 View Complete Implementation : conftest.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : elastic
def pytest_configure(config):
    try:
        from django.conf import settings
    except ImportError:
        settings = None
    if settings is not None and not settings.configured:
        import django

        settings_dict = dict(
            SECRET_KEY="42",
            DATABASES={
                "default": {
                    "ENGINE": "django.db.backends.sqlite3",
                    "NAME": "elasticapm_tests.db",
                    "TEST_NAME": "elasticapm_tests.db",
                    "TEST": {"NAME": "elasticapm_tests.db"},
                }
            },
            TEST_DATABASE_NAME="elasticapm_tests.db",
            INSTALLED_APPS=[
                "django.contrib.auth",
                "django.contrib.admin",
                "django.contrib.sessions",
                "django.contrib.sites",
                "django.contrib.redirects",
                "django.contrib.contenttypes",
                "elasticapm.contrib.django",
                "tests.contrib.django.testapp",
            ],
            ROOT_URLCONF="tests.contrib.django.testapp.urls",
            DEBUG=False,
            SITE_ID=1,
            BROKER_HOST="localhost",
            BROKER_PORT=5672,
            BROKER_USER="guest",
            BROKER_PastWORD="guest",
            BROKER_VHOST="/",
            CELERY_ALWAYS_EAGER=True,
            TEMPLATE_DEBUG=False,
            TEMPLATE_DIRS=[BASE_TEMPLATE_DIR],
            ALLOWED_HOSTS=["*"],
            TEMPLATES=[
                {
                    "BACKEND": "django.template.backends.django.DjangoTemplates",
                    "DIRS": [BASE_TEMPLATE_DIR],
                    "OPTIONS": {
                        "context_processors": ["django.contrib.auth.context_processors.auth"],
                        "loaders": ["django.template.loaders.filesystem.Loader"],
                        "debug": False,
                    },
                }
            ],
            ELASTIC_APM={
                "METRICS_INTERVAL": "0ms",
                "TRANSPORT_CLast": "tests.fixtures.DummyTransport",
            },  # avoid autostarting the metrics collector thread
        )
        settings_dict.update(
            **middleware_setting(
                django.VERSION,
                [
                    "django.contrib.sessions.middleware.SessionMiddleware",
                    "django.contrib.auth.middleware.AuthenticationMiddleware",
                    "django.contrib.messages.middleware.MessageMiddleware",
                ],
            )
        )
        settings.configure(**settings_dict)
        if hasattr(django, "setup"):
            django.setup()

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : evansmurithi
def pytest_configure():
    from django.conf import settings

    MIDDLEWARE = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    )

    settings.configure(
        BASE_DIR=os.path.dirname(os.path.abspath(__file__)),
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.test_app.urls',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
            },
        ],
        MIDDLEWARE=MIDDLEWARE,
        MIDDLEWARE_CLastES=MIDDLEWARE,
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',
            'rest_framework',
            'rest_framework.authtoken',
            'tests.test_app',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : FutureMind
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SECRET_KEY='not important here',
        ROOT_URLCONF='tests.urls',
        MIDDLEWARE_CLastES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',

            'tests',
            'rest_framework',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
        REST_FRAMEWORK={
            'EXCEPTION_HANDLER':
            'rest_framework_friendly_errors.handlers.friendly_exception_handler'
        },
        LANGUAGE_CODE='pl'
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : HealthByRo
def pytest_configure():
    import django
    from django.conf import settings
    from django.core.management import call_command

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
        },
        SITE_ID=1,
        SECRET_KEY="not very secret in tests",
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL="/static/",
        ROOT_URLCONF="tests.urls",
        TEMPLATE_LOADERS=(
            "django.template.loaders.filesystem.Loader",
            "django.template.loaders.app_directories.Loader",
        ),
        MIDDLEWARE_CLastES=(
            "django.middleware.common.CommonMiddleware",
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.middleware.csrf.CsrfViewMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware",
            "jwt_devices.middleware.PermittedHeadersMiddleware",
        ),
        INSTALLED_APPS=(
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            "django.contrib.sites",
            "django.contrib.messages",
            "django.contrib.staticfiles",
            "rest_framework",
            "rest_framework_jwt",
            "jwt_devices",
            "tests",
        ),
        PastWORD_HASHERS=("django.contrib.auth.hashers.MD5PastwordHasher",),
        REST_FRAMEWORK={
            "DEFAULT_AUTHENTICATION_CLastES": [
                "jwt_devices.authentication.PermanentTokenAuthentication"
            ]
        },
    )

    try:
        import oauth_provider  # NOQA
        import oauth2  # NOQA
    except ImportError:
        past
    else:
        settings.INSTALLED_APPS += ("oauth_provider",)

    try:
        if django.VERSION >= (1, 8):
            # django-oauth2-provider does not support Django1.8
            raise ImportError
        import provider  # NOQA
    except ImportError:
        past
    else:
        settings.INSTALLED_APPS += ("provider", "provider.oauth2")

    try:
        import django

        django.setup()
    except AttributeError:
        past

    call_command("migrate")
    call_command("makemigrations", "--dry-run", "--check")

0 View Complete Implementation : tests.py
Copyright MIT License
Author : jazzband
def main():
    """
    Standalone django model test with a 'memory-only-django-installation'.
    You can play with a django model without a complete django app installation.
    http://www.djangosnippets.org/snippets/1044/
    """
    os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
    from django.conf import global_settings

    global_settings.SECRET_KEY = "snakeoil"
    global_settings.TIME_ZONE = "UTC"

    global_settings.INSTALLED_APPS = ("django.contrib.contenttypes", "django_ical")
    global_settings.DATABASES = {
        "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
    }

    global_settings.MIDDLEWARE_CLastES = (
        "django.middleware.common.CommonMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
    )

    if django.VERSION > (1, 7):
        django.setup()

    from django.test.utils import get_runner

    test_runner = get_runner(global_settings)

    test_runner = test_runner()
    failures = test_runner.run_tests(["django_ical"])
    sys.exit(failures)

0 View Complete Implementation : cli.py
Copyright MIT License
Author : learningequality
@main.command(cls=KolibriDjangoCommand, help="Start the Kolibri process")
@click.option(
    "--port",
    default=OPTIONS["Deployment"]["HTTP_PORT"],
    type=int,
    help="Port on which Kolibri is being served",
)
@click.option(
    "--background/--foreground",
    default=True,
    help="Run Kolibri as a background process",
)
def start(port, background):
    """
    Start the server on given port.
    """

    serve_http = OPTIONS["Server"]["CHERRYPY_START"]

    if serve_http:
        # Check if the port is occupied
        check_other_kolibri_running(port)

    create_startup_lock(port)

    # Check if the content directory exists when Kolibri runs after the first time.
    check_content_directory_exists_and_writable()

    # Clear old sessions up
    call_command("clearsessions")

    # On Mac, Python crashes when forking the process, so prevent daemonization until we can figure out
    # a better fix. See https://github.com/learningequality/kolibri/issues/4821
    if sys.platform == "darwin":
        background = False

    if not background:
        logger.info("Running Kolibri")

    else:
        logger.info("Running Kolibri as background process")

    if serve_http:

        __, urls = server.get_urls(listen_port=port)
        if not urls:
            logger.error(
                "Could not detect an IP address that Kolibri binds to, but try "
                "opening up the following addresses:\n"
            )
            urls = [
                "http://{}:{}".format(ip, port) for ip in ("localhost", "127.0.0.1")
            ]
        else:
            logger.info("Kolibri running on:\n")
        for addr in urls:
            sys.stderr.write("\t{}\n".format(addr))
        sys.stderr.write("\n")
    else:
        logger.info("Starting Kolibri background workers")

    # Daemonize at this point, no more user output is needed
    if background:

        from django.conf import settings

        kolibri_log = settings.LOGGING["handlers"]["file"]["filename"]
        logger.info("Going to background mode, logging to {0}".format(kolibri_log))

        kwargs = {}
        # Truncate the file
        if os.path.isfile(server.DAEMON_LOG):
            open(server.DAEMON_LOG, "w").truncate()
        kwargs["out_log"] = server.DAEMON_LOG
        kwargs["err_log"] = server.DAEMON_LOG

        become_daemon(**kwargs)

    server.start(port=port, serve_http=serve_http)

0 View Complete Implementation : makemessages.py
Copyright Apache License 2.0
Author : edisonlz
    def handle_noargs(self, *args, **options):
        locale = options.get('locale')
        self.domain = options.get('domain')
        self.verbosity = int(options.get('verbosity'))
        process_all = options.get('all')
        extensions = options.get('extensions')
        self.symlinks = options.get('symlinks')
        ignore_patterns = options.get('ignore_patterns')
        if options.get('use_default_ignore_patterns'):
            ignore_patterns += ['CVS', '.*', '*~', '*.pyc']
        self.ignore_patterns = list(set(ignore_patterns))
        self.wrap = '--no-wrap' if options.get('no_wrap') else ''
        self.location = '--no-location' if options.get('no_location') else ''
        self.no_obsolete = options.get('no_obsolete')
        self.keep_pot = options.get('keep_pot')

        if self.domain not in ('django', 'djangojs'):
            raise CommandError("currently makemessages only supports domains "
                               "'django' and 'djangojs'")
        if self.domain == 'djangojs':
            exts = extensions if extensions else ['js']
        else:
            exts = extensions if extensions else ['html', 'txt']
        self.extensions = handle_extensions(exts)

        if (locale is None and not process_all) or self.domain is None:
            raise CommandError("Type '%s help %s' for usage information." % (
                                os.path.basename(sys.argv[0]), sys.argv[1]))

        if self.verbosity > 1:
            self.stdout.write('examining files with the extensions: %s\n'
                             % get_text_list(list(self.extensions), 'and'))

        # Need to ensure that the i18n framework is enabled
        from django.conf import settings
        if settings.configured:
            settings.USE_I18N = True
        else:
            settings.configure(USE_I18N = True)

        self.invoked_for_django = False
        if os.path.isdir(os.path.join('conf', 'locale')):
            localedir = os.path.abspath(os.path.join('conf', 'locale'))
            self.invoked_for_django = True
            # Ignoring all contrib apps
            self.ignore_patterns += ['contrib/*']
        elif os.path.isdir('locale'):
            localedir = os.path.abspath('locale')
        else:
            raise CommandError("This script should be run from the Django Git "
                    "tree or your project or app tree. If you did indeed run it "
                    "from the Git checkout or your project or application, "
                    "maybe you are just missing the conf/locale (in the django "
                    "tree) or locale (for project and application) directory? It "
                    "is not created automatically, you have to create it by hand "
                    "if you want to enable i18n for your project or application.")

        check_programs('xgettext')

        potfile = self.build_pot_file(localedir)

        # Build po files for each selected locale
        locales = []
        if locale is not None:
            locales += locale.split(',') if not isinstance(locale, list) else locale
        elif process_all:
            locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
            locales = [os.path.basename(l) for l in locale_dirs]

        if locales:
            check_programs('msguniq', 'msgmerge', 'msgattrib')

        try:
            for locale in locales:
                if self.verbosity > 0:
                    self.stdout.write("processing locale %s\n" % locale)
                self.write_po_file(potfile, locale)
        finally:
            if not self.keep_pot and os.path.exists(potfile):
                os.unlink(potfile)

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : lock8
def pytest_configure():
    import django
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SOUTH_TESTS_MIGRATE=False,
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        LANGUAGE_CODE='en-us',
        TIME_ZONE='UTC',
        USE_TZ=True,
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATE_LOADERS=(
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ),
        MIDDLEWARE_CLastES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.messages',
            'django.contrib.staticfiles',

            'tests',
            'refreshtoken',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
        REST_FRAMEWORK={
            'DEFAULT_PERMISSION_CLastES': (
                'refreshtoken.permissions.IsOwnerOrAdmin',
            ),
            'DEFAULT_AUTHENTICATION_CLastES': (
                'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
            ),
        },
        JWT_AUTH={
            'JWT_ALLOW_REFRESH': True,
        },
    )

    django.setup()

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : luizalabs
def pytest_configure():
    global _SETTINGS

    try:
        import django
        from django.conf import settings

        settings.configure(POOL_OF_RAMOS=POOL_OF_RAMOS)
        django.setup()

        _SETTINGS = settings
    except ImportError:
        try:
            import os

            os.environ.setdefault('SIMPLE_SETTINGS', 'conftest')

            from simple_settings import settings

            settings.configure(POOL_OF_RAMOS=POOL_OF_RAMOS)

            _SETTINGS = settings
        except ImportError:
            import ramos
            ramos.configure(pools=POOL_OF_RAMOS)

0 View Complete Implementation : plugin.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _reconfigureLogging(self):
        # Reconfigure the logging based on the debug mode of Django.
        from django.conf import settings

        if settings.DEBUG:
            # In debug mode, force logging to debug mode.
            logger.set_verbosity(3)

            # When not in the developer environment, patch Django to not
            # use the debug cursor. This is needed or Django will store in
            # memory every SQL query made.
            from provisioningserver.config import is_dev_environment

            if not is_dev_environment():
                from django.db.backends.base import base
                from django.db.backends.utils import CursorWrapper

                base.BaseDatabaseWrapper.make_debug_cursor = lambda self, cursor: CursorWrapper(
                    cursor, self
                )

0 View Complete Implementation : test_django.py
Copyright MIT License
Author : hashedin
    def configure_django():
        from django.conf import settings
        import django

        settings.configure(
            DEBUG_PROPAGATE_EXCEPTIONS=True,
            DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                                   'NAME': ':memory:'}},
            SITE_ID=1,
            SECRET_KEY='not very secret in tests',
            USE_I18N=True,
            USE_L10N=True,
            STATIC_URL='/static/',
            ROOT_URLCONF='tests.urls',
            TEMPLATE_LOADERS=(
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ),
            MIDDLEWARE_CLastES=(
                'django.middleware.common.CommonMiddleware',
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.middleware.csrf.CsrfViewMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
            ),
            INSTALLED_APPS=(
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.sites',
                'django.contrib.messages',
                'django.contrib.staticfiles',
            ),
            PastWORD_HASHERS=(
                'django.contrib.auth.hashers.SHA1PastwordHasher',
                'django.contrib.auth.hashers.PBKDF2PastwordHasher',
                'django.contrib.auth.hashers.PBKDF2SHA1PastwordHasher',
                'django.contrib.auth.hashers.BCryptPastwordHasher',
                'django.contrib.auth.hashers.MD5PastwordHasher',
                'django.contrib.auth.hashers.CryptPastwordHasher',
            ),
        )
        django.setup()

0 View Complete Implementation : simpletags.py
Copyright MIT License
Author : newpanjing
@register.simple_tag()
def get_language():
    from django.conf import settings
    return settings.LANGUAGE_CODE.lower()

0 View Complete Implementation : simpletags.py
Copyright MIT License
Author : newpanjing
@register.filter
def get_language_code(val):
    from django.conf import settings
    return settings.LANGUAGE_CODE.lower()

0 View Complete Implementation : makemessages.py
Copyright GNU General Public License v2.0
Author : blackye
def make_messages(locale=None, domain='django', verbosity=1, all=False,
        extensions=None, symlinks=False, ignore_patterns=None, no_wrap=False,
        no_location=False, no_obsolete=False, stdout=sys.stdout):
    """
    Uses the ``locale/`` directory from the Django Git tree or an
    application/project to process all files with translatable literals for
    the :param domain: domain and :param locale: locale.
    """
    # Need to ensure that the i18n framework is enabled
    from django.conf import settings
    if settings.configured:
        settings.USE_I18N = True
    else:
        settings.configure(USE_I18N = True)

    if ignore_patterns is None:
        ignore_patterns = []

    invoked_for_django = False
    if os.path.isdir(os.path.join('conf', 'locale')):
        localedir = os.path.abspath(os.path.join('conf', 'locale'))
        invoked_for_django = True
        # Ignoring all contrib apps
        ignore_patterns += ['contrib/*']
    elif os.path.isdir('locale'):
        localedir = os.path.abspath('locale')
    else:
        raise CommandError("This script should be run from the Django Git "
                "tree or your project or app tree. If you did indeed run it "
                "from the Git checkout or your project or application, "
                "maybe you are just missing the conf/locale (in the django "
                "tree) or locale (for project and application) directory? It "
                "is not created automatically, you have to create it by hand "
                "if you want to enable i18n for your project or application.")

    if domain not in ('django', 'djangojs'):
        raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'")

    if (locale is None and not all) or domain is None:
        message = "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1])
        raise CommandError(message)

    # We require gettext version 0.15 or newer.
    output, errors, status = _popen('xgettext --version')
    if status != STATUS_OK:
        raise CommandError("Error running xgettext. Note that Django "
                    "internationalization requires GNU gettext 0.15 or newer.")
    match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output)
    if match:
        xversion = (int(match.group('major')), int(match.group('minor')))
        if xversion < (0, 15):
            raise CommandError("Django internationalization requires GNU "
                    "gettext 0.15 or newer. You are using version %s, please "
                    "upgrade your gettext toolset." % match.group())

    locales = []
    if locale is not None:
        locales.append(str(locale))
    elif all:
        locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
        locales = [os.path.basename(l) for l in locale_dirs]

    wrap = '--no-wrap' if no_wrap else ''
    location = '--no-location' if no_location else ''

    for locale in locales:
        if verbosity > 0:
            stdout.write("processing language %s\n" % locale)
        basedir = os.path.join(localedir, locale, 'LC_MESSAGES')
        if not os.path.isdir(basedir):
            os.makedirs(basedir)

        pofile = os.path.join(basedir, '%s.po' % str(domain))
        potfile = os.path.join(basedir, '%s.pot' % str(domain))

        if os.path.exists(potfile):
            os.unlink(potfile)

        for dirpath, file in find_files(".", ignore_patterns, verbosity,
                stdout, symlinks=symlinks):
            try:
                process_file(file, dirpath, potfile, domain, verbosity, extensions,
                        wrap, location, stdout)
            except UnicodeDecodeError:
                stdout.write("UnicodeDecodeError: skipped file %s in %s" % (file, dirpath))

        if os.path.exists(potfile):
            write_po_file(pofile, potfile, domain, locale, verbosity, stdout,
                    not invoked_for_django, wrap, location, no_obsolete)

0 View Complete Implementation : simpletags.py
Copyright MIT License
Author : newpanjing
@register.simple_tag
def has_enable_admindoc():
    from django.conf import settings
    apps = settings.INSTALLED_APPS
    return 'django.contrib.admindocs' in apps

0 View Complete Implementation : cli.py
Copyright MIT License
Author : learningequality
@main.command(cls=KolibriDjangoCommand, help="Start worker processes")
@click.option(
    "--port",
    default=OPTIONS["Deployment"]["HTTP_PORT"],
    type=int,
    help="Port on which to run Kolibri services",
)
@click.option(
    "--background/--foreground",
    default=True,
    help="Run Kolibri services as a background task",
)
def services(port, background):
    """
    Start the kolibri background services.
    """

    create_startup_lock(None)

    logger.info("Starting Kolibri background services")

    # Daemonize at this point, no more user output is needed
    if background:

        from django.conf import settings

        kolibri_log = settings.LOGGING["handlers"]["file"]["filename"]
        logger.info("Going to background mode, logging to {0}".format(kolibri_log))

        kwargs = {}
        # Truncate the file
        if os.path.isfile(server.DAEMON_LOG):
            open(server.DAEMON_LOG, "w").truncate()
        kwargs["out_log"] = server.DAEMON_LOG
        kwargs["err_log"] = server.DAEMON_LOG

        become_daemon(**kwargs)

    server.start(port=port, serve_http=False)

0 View Complete Implementation : conftest.py
Copyright ISC License
Author : raphaelgyory
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': ':memory:'}},
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATE_LOADERS=(
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ),
        MIDDLEWARE_CLastES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.messages',
            'django.contrib.staticfiles',

            'rest_framework',
            'rest_framework.authtoken',
            'tests',

            # the module
            'rest_messaging',
            'rest_messaging_centrifugo',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.SHA1PastwordHasher',
            'django.contrib.auth.hashers.PBKDF2PastwordHasher',
            'django.contrib.auth.hashers.PBKDF2SHA1PastwordHasher',
            'django.contrib.auth.hashers.BCryptPastwordHasher',
            'django.contrib.auth.hashers.MD5PastwordHasher',
            'django.contrib.auth.hashers.CryptPastwordHasher',
        ),
        # Centrifugo
        CENTRIFUGO_PORT=8802,
        CENTRIFUGO_MESSAGE_NAMESPACE="messages",
        CENTRIFUGO_THREAD_NAMESPACE="threads",
        CENTRIFUGE_ADDRESS='http://localhost:{0}/'.format(8802),
        CENTRIFUGE_SECRET='secret',
        CENTRIFUGE_TIMEOUT=5,
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : simpletags.py
Copyright MIT License
Author : newpanjing
def __get_config(name):
    from django.conf import settings
    value = os.environ.get(name, getattr(settings, name, None))

    return value

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : aaronn
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SITE_ID=1,
        SECRET_KEY='_',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [],
                'APP_DIRS': True,
                'OPTIONS': {
                    'context_processors': [
                        'django.template.context_processors.debug',
                        'django.template.context_processors.request',
                        'django.contrib.auth.context_processors.auth',
                        'django.contrib.messages.context_processors.messages',
                    ],
                },
            },
        ],
        MIDDLEWARE_CLastES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.messages',
            'django.contrib.staticfiles',
            'rest_framework',
            'rest_framework.authtoken',
            'drfpastwordless',
            'tests',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
        AUTH_USER_MODEL='tests.CustomUser',
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : basehttp.py
Copyright GNU General Public License v2.0
Author : blackye
def get_internal_wsgi_application():
    """
    Loads and returns the WSGI application as configured by the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
    for Django's internal servers (runserver, runfcgi); external WSGI servers
    should just be configured to point to the correct application object
    directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), we just return
    whatever ``django.core.wsgi.get_wsgi_application`` returns.

    """
    from django.conf import settings
    app_path = getattr(settings, 'WSGI_APPLICATION')
    if app_path is None:
        return get_wsgi_application()
    module_name, attr = app_path.rsplit('.', 1)
    try:
        mod = import_module(module_name)
    except ImportError as e:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "could not import module '%s': %s" % (app_path, module_name, e))
    try:
        app = getattr(mod, attr)
    except AttributeError as e:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "can't find '%s' in module '%s': %s"
            % (app_path, attr, module_name, e))

    return app

0 View Complete Implementation : conftest.py
Copyright ISC License
Author : raphaelgyory
def pytest_configure():
    from django.conf import settings
    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': ':memory:'}},
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATE_LOADERS=(
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ),
        MIDDLEWARE_CLastES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
            'rest_messaging.middleware.MessagingMiddleware'
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.messages',
            'django.contrib.staticfiles',

            'rest_framework',
            'rest_framework.authtoken',
            'tests',

            # rest_messaging
            'rest_messaging',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.SHA1PastwordHasher',
            'django.contrib.auth.hashers.PBKDF2PastwordHasher',
            'django.contrib.auth.hashers.PBKDF2SHA1PastwordHasher',
            'django.contrib.auth.hashers.BCryptPastwordHasher',
            'django.contrib.auth.hashers.MD5PastwordHasher',
            'django.contrib.auth.hashers.CryptPastwordHasher',
        ),
        REST_FRAMEWORK={
            'DEFAULT_PAGINATION_CLast': 'rest_framework.pagination.PageNumberPagination',
            'PAGE_SIZE': 100,
            'DEFAULT_PAGINATION_SERIALIZER_CLast': 'rest_framework.pagination.PaginationSerializer',  # 3.0
            'PAGINATE_BY_PARAM': 100,  # 3.0
            'PAGINATE_BY': 10,  # 3.0
            'MAX_PAGINATE_BY': 100  # 3.0
        }
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : run_test.py
Copyright MIT License
Author : chaitin
def setup_django_environment():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            "default": dj_database_url.config(env="DATABASE_URL",
                                              default="postgres://test:[email protected]/test",
                                              conn_max_age=20)
        },
        SECRET_KEY="not very secret in tests",
        USE_I18N=True,
        USE_L10N=True,
        USE_TZ=True,
        TIME_ZONE="Asia/Shanghai",
        INSTALLED_APPS=(
            "pg_parsationing",
            "tests",
        ),
        LOGGING={
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "standard": {
                    "format": "[%(asctime)s] %(message)s",
                    "datefmt": "%Y-%m-%d %H:%M:%S"
                }
            },
            "handlers": {
                "console": {
                    "level": "DEBUG",
                    "clast": "logging.StreamHandler",
                    "formatter": "standard"
                }
            },
            "loggers": {
                "pg_parsationing.shortcuts": {
                    "handlers": ["console"],
                    "level": "DEBUG",
                    "propagate": False,
                },
                "pg_parsationing.patch.schema": {
                    "handlers": ["console"],
                    "level": "DEBUG",
                    "propagate": False,
                },
            },
        }
    )

    django.setup()

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : chessbr
def pytest_configure():
    from django.conf import settings

    MIDDLEWARE = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    )

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='rest_jwt_permission_tests.urls',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True
            },
        ],
        MIDDLEWARE=MIDDLEWARE,
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',
            'rest_framework',
            'rest_jwt_permission',
            'rest_jwt_permission_tests',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
        AUTHENTICATION_BACKENDS = (
            'django.contrib.auth.backends.ModelBackend',
        ),
        JWT_AUTH = {
            "JWT_SECRET_KEY": "super-secret"
        },
        REST_FRAMEWORK = {
            "TEST_REQUEST_DEFAULT_FORMAT": 'json'
        }
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : test_django.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : p1c2u
    @pytest.fixture(autouse=True, scope='module')
    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),
        )

0 View Complete Implementation : templates.py
Copyright GNU General Public License v2.0
Author : blackye
    def handle(self, app_or_project, name, target=None, **options):
        self.app_or_project = app_or_project
        self.paths_to_remove = []
        self.verbosity = int(options.get('verbosity'))

        # If it's not a valid directory name.
        if not re.search(r'^[_a-zA-Z]\w*$', name):
            # Provide a smart error message, depending on the error.
            if not re.search(r'^[_a-zA-Z]', name):
                message = ('make sure the name begins '
                           'with a letter or underscore')
            else:
                message = 'use only numbers, letters and underscores'
            raise CommandError("%r is not a valid %s name. Please %s." %
                               (name, app_or_project, message))

        # if some directory is given, make sure it's nicely expanded
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = os.path.abspath(path.expanduser(target))
            if not os.path.exists(top_dir):
                raise CommandError("Destination directory '%s' does not "
                                   "exist, please create it first." % top_dir)

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        extra_files = []
        for file in options.get('files'):
            extra_files.extend(map(lambda x: x.strip(), file.split(',')))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))
            self.stdout.write("Rendering %s template files with "
                              "filenames: %s\n" %
                              (app_or_project, ', '.join(extra_files)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project

        context = Context(dict(options, **{
            base_name: name,
            base_directory: top_dir,
        }), autoescape=False)

        # Setup a stub settings environment for template rendering
        from django.conf import settings
        if not settings.configured:
            settings.configure()

        template_dir = self.handle_template(options.get('template'),
                                            base_subdir)
        prefix_length = len(template_dir) + 1

        for root, dirs, files in os.walk(template_dir):

            path_rest = root[prefix_length:]
            relative_dir = path_rest.replace(base_name, name)
            if relative_dir:
                target_dir = path.join(top_dir, relative_dir)
                if not path.exists(target_dir):
                    os.mkdir(target_dir)

            for dirname in dirs[:]:
                if dirname.startswith('.') or dirname == '__pycache__':
                    dirs.remove(dirname)

            for filename in files:
                if filename.endswith(('.pyo', '.pyc', '.py.clast')):
                    # Ignore some files as they cause various breakages.
                    continue
                old_path = path.join(root, filename)
                new_path = path.join(top_dir, relative_dir,
                                     filename.replace(base_name, name))
                if path.exists(new_path):
                    raise CommandError("%s already exists, overlaying a "
                                       "project or app into an existing "
                                       "directory won't replace conflicting "
                                       "files" % new_path)

                # Only render the Python files, as we don't want to
                # accidentally render Django templates files
                with open(old_path, 'rb') as template_file:
                    content = template_file.read()
                if filename.endswith(extensions) or filename in extra_files:
                    content = content.decode('utf-8')
                    template = Template(content)
                    content = template.render(context)
                    content = content.encode('utf-8')
                with open(new_path, 'wb') as new_file:
                    new_file.write(content)

                if self.verbosity >= 2:
                    self.stdout.write("Creating %s\n" % new_path)
                try:
                    shutil.copymode(old_path, new_path)
                    self.make_writeable(new_path)
                except OSError:
                    self.stderr.write(
                        "Notice: Couldn't set permission bits on %s. You're "
                        "probably using an uncommon filesystem setup. No "
                        "problem." % new_path, self.style.NOTICE)

        if self.paths_to_remove:
            if self.verbosity >= 2:
                self.stdout.write("Cleaning up temporary files.\n")
            for path_to_remove in self.paths_to_remove:
                if path.isfile(path_to_remove):
                    os.remove(path_to_remove)
                else:
                    shutil.rmtree(path_to_remove,
                                  onerror=rmtree_errorhandler)

0 View Complete Implementation : conftest.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : craigds
def pytest_configure():
    from django.conf import settings

    # Best-guess the db user name
    db_user = os.environ.get('PGUSER')
    if not db_user:
        # On MacOS, brew installs postgres with the superuser account called $USER
        db_user = os.environ.get('USER')
        if os.environ.get('CI'):
            # On travis superuser is called postgres
            db_user = 'postgres'

    if not db_user:
        db_user = 'postgres'

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': 'mpathy_tests',
                'USER': db_user,
                'PastWORD': '',
                'HOST': 'localhost',
                'TEST': {
                    'NAME': 'mpathy_tests',
                }
            }
        },
        SECRET_KEY='hunter2',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
            },
        ],
        MIDDLEWARE=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ),
        INSTALLED_APPS=(
            'mpathy',
            'tests',
        ),
    )
    django.setup()

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : davesque
def pytest_configure():
    from django.conf import settings

    MIDDLEWARE = (
        'django.middleware.common.CommonMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
    )

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
            },
        ],
        MIDDLEWARE=MIDDLEWARE,
        MIDDLEWARE_CLastES=MIDDLEWARE,
        INSTALLED_APPS=(
            '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',

            'tests',
        ),
        PastWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PastwordHasher',
        ),
    )

    try:
        import django
        django.setup()
    except AttributeError:
        past

0 View Complete Implementation : conftest.py
Copyright MIT License
Author : eamigo86
def pytest_configure(config):
    from django.conf import settings

    settings.configure(
        ALLOWED_HOSTS=["*"],
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
        },
        SITE_ID=1,
        SECRET_KEY="not very secret in tests",
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL="/static/",
        ROOT_URLCONF="tests.urls",
        TEMPLATES=[
            {
                "BACKEND": "django.template.backends.django.DjangoTemplates",
                "APP_DIRS": True,
                "OPTIONS": {"debug": True},  # We want template errors to raise
            }
        ],
        MIDDLEWARE=(
            "django.middleware.common.CommonMiddleware",
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware",
            "django.middleware.csrf.CsrfViewMiddleware",
        ),
        INSTALLED_APPS=(
            "django.contrib.admin",
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            "django.contrib.sites",
            "django.contrib.staticfiles",
            "graphene_django",
            "tests",
        ),
        PastWORD_HASHERS=("django.contrib.auth.hashers.MD5PastwordHasher",),
        GRAPHENE={"SCHEMA": "tests.schema.schema"},
        AUTHENTICATION_BACKENDS=(
            "django.contrib.auth.backends.ModelBackend",
            "guardian.backends.ObjectPermissionBackend",
        ),
    )

    # FIXME(eclar): necessary ?
    if config.getoption("--no-pkgroot"):
        sys.path.pop(0)

        # import rest_framework before pytest re-adds the package root directory.
        import graphene_django_extras

        package_dir = os.path.join(os.getcwd(), "graphene_django_extras")
        astert not graphene_django_extras.__file__.startswith(package_dir)

    # Manifest storage will raise an exception if static files are not present (ie, a packaging failure).
    if config.getoption("--staticfiles"):
        import graphene_django_extras

        settings.STATIC_ROOT = os.path.join(
            os.path.dirname(graphene_django_extras.__file__), "static-root"
        )
        settings.STATICFILES_STORAGE = (
            "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
        )

    django.setup()

    if config.getoption("--staticfiles"):
        management.call_command("collectstatic", verbosity=0, interactive=False)

0 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def execute(self, *args, **options):
        """
        Try to execute this command, performing model validation if
        needed (as controlled by the attribute
        ``self.requires_model_validation``, except if force-skipped).
        """
        self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
        self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)

        if self.can_import_settings:
            from django.conf import settings

        saved_locale = None
        if not self.leave_locale_alone:
            # Only mess with locales if we can astume we have a working
            # settings file, because django.utils.translation requires settings
            # (The final saying about whether the i18n machinery is active will be
            # found in the value of the USE_I18N setting)
            if not self.can_import_settings:
                raise CommandError("Incompatible values of 'leave_locale_alone' "
                                   "(%s) and 'can_import_settings' (%s) command "
                                   "options." % (self.leave_locale_alone,
                                                 self.can_import_settings))
            # Switch to US English, because django-admin.py creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.activate('en-us')

        try:
            if self.requires_model_validation and not options.get('skip_validation'):
                self.validate()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;"))
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)