Python django.conf() Examples

The following are 30 code examples of django.conf(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django , or try the search function .
Example #1
Source File: conf.py    From django-rest-framework-simplejwt with MIT License 6 votes vote down vote up
def django_configure():
    from django.conf import settings

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

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

    try:
        import django
        django.setup()
    except AttributeError:
        pass 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def run_manage(self, args, settings_file=None):
        def safe_remove(path):
            try:
                os.remove(path)
            except OSError:
                pass

        conf_dir = os.path.dirname(conf.__file__)
        template_manage_py = os.path.join(conf_dir, 'project_template', 'manage.py-tpl')

        test_manage_py = os.path.join(self.test_dir, 'manage.py')
        shutil.copyfile(template_manage_py, test_manage_py)

        with open(test_manage_py, 'r') as fp:
            manage_py_contents = fp.read()
        manage_py_contents = manage_py_contents.replace(
            "{{ project_name }}", "test_project")
        with open(test_manage_py, 'w') as fp:
            fp.write(manage_py_contents)
        self.addCleanup(safe_remove, test_manage_py)

        return self.run_test('./manage.py', args, settings_file) 
Example #3
Source File: runtests.py    From django-subscriptions with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # First configure settings, then call django.setup() to initialise
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)
    import django

    django.setup()

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

    TestRunner = get_runner(settings)

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

    settings.configure(
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3"}
        },
        INSTALLED_APPS=[
            "django.contrib.auth",
            "django.contrib.contenttypes",
            # "django.contrib.sites",
            "taggit",
            "taggit_labels",
            "test_app",
        ],
        MIDDLEWARE_CLASSES=(),
        SITE_ID=1,
    )
    try:
        django.setup()
    except AttributeError:
        # Django 1.7 or lower
        pass 
Example #5
Source File: conf.py    From django-ftpserver with MIT License 6 votes vote down vote up
def setup_django():
    import django
    from django.conf import settings
    if not settings.configured:
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': ':memory:',
                }
            },
            INSTALLED_APPS=(
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django_ftpserver',
            )
        )
    django.setup()
    from django.apps import apps
    if not apps.ready:
        apps.populate() 
Example #6
Source File: plugin.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
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
                ) 
Example #7
Source File: migraterunner.py    From django-partial-index with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #8
Source File: runner.py    From django-partial-index with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #9
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 6 votes vote down vote up
def read_template_source(filename):
    """Read the source of a Django template, returning the Unicode text."""
    # Import this late to be sure we don't trigger settings machinery too
    # early.
    from django.conf import settings

    if not settings.configured:
        settings.configure()

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

    return text 
Example #10
Source File: __init__.py    From django-rest-framework-cache with GNU General Public License v3.0 6 votes vote down vote up
def configure():
    from django.conf import settings

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

            'rest_framework',
            'tests',
        ),
    )

    import django
    django.setup() 
Example #11
Source File: runtests.py    From pwned-passwords-django with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)

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

    django.setup()

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

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example #12
Source File: setup.py    From django-cryptography with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests(self):
        import django
        django.setup()

        from django.conf import settings
        from django.test.utils import get_runner

        TestRunner = get_runner(settings, self.testrunner)

        test_runner = TestRunner(
            pattern=self.pattern,
            top_level=self.top_level_directory,
            verbosity=self.verbose,
            interactive=(not self.noinput),
            failfast=self.failfast,
            keepdb=self.keepdb,
            reverse=self.reverse,
            debug_sql=self.debug_sql,
            output_dir=self.output_dir)
        failures = test_runner.run_tests(self.test_labels)

        sys.exit(bool(failures)) 
Example #13
Source File: utils.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def verbose_lookup_expr(lookup_expr):
    """
    Get a verbose, more humanized expression for a given ``lookup_expr``.
    Each part in the expression is looked up in the ``FILTERS_VERBOSE_LOOKUPS``
    dictionary. Missing keys will simply default to itself.

    ex::

        >>> verbose_lookup_expr('year__lt')
        'year is less than'

        # with `FILTERS_VERBOSE_LOOKUPS = {}`
        >>> verbose_lookup_expr('year__lt')
        'year lt'

    """
    from .conf import settings as app_settings

    VERBOSE_LOOKUPS = app_settings.VERBOSE_LOOKUPS or {}
    lookups = [
        force_text(VERBOSE_LOOKUPS.get(lookup, _(lookup)))
        for lookup in lookup_expr.split(LOOKUP_SEP)
    ]

    return ' '.join(lookups) 
Example #14
Source File: templates.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example #15
Source File: setup.py    From django-calaccess-campaign-browser with MIT License 6 votes vote down vote up
def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={
                'default': {
                    'NAME': ':memory:',
                    'ENGINE': 'django.db.backends.sqlite3'
                }
            },
            INSTALLED_APPS=('calaccess_campaign_browser',),
            MIDDLEWARE_CLASSES=()
        )
        from django.core.management import call_command
        import django
        if django.VERSION[:2] >= (1, 7):
            django.setup()
        call_command('test', 'calaccess_campaign_browser') 
Example #16
Source File: models.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_current(self):
        """
        Returns the current ``UserSettings`` based on the SITE_ID in the
        project's settings. The ``UserSettings`` object is cached the first
        time it's retrieved from the database.
        """
        from django.conf import settings
        try:
            site_id = settings.SITE_ID
        except AttributeError:
            raise ImproperlyConfigured(
                'You\'re using the Django "sites framework" without having '
                'set the SITE_ID setting. Create a site in your database and '
                'set the SITE_ID setting to fix this error.')

        try:
            current_usersettings = USERSETTINGS_CACHE[site_id]
        except KeyError:
            current_usersettings = self.get(site_id=site_id)
            USERSETTINGS_CACHE[site_id] = current_usersettings
        return current_usersettings 
Example #17
Source File: forms.py    From django-payfast with MIT License 6 votes vote down vote up
def clean(self):
        self.ip = self.request.META.get(conf.IP_HEADER, None)
        if not is_payfast_ip_address(self.ip):
            raise forms.ValidationError('untrusted ip: %s' % self.ip)

        # Verify signature
        sig = api.itn_signature(self.data)
        if sig != self.cleaned_data['signature']:
            raise forms.ValidationError('Signature is invalid: %s != %s' % (
                sig, self.cleaned_data['signature'],))

        if conf.USE_POSTBACK:
            is_valid = api.data_is_valid(self.request.POST, conf.SERVER)
            if is_valid is None:
                raise forms.ValidationError('Postback fails')
            if not is_valid:
                raise forms.ValidationError('Postback validation fails')

        return self.cleaned_data 
Example #18
Source File: forms.py    From django-payfast with MIT License 6 votes vote down vote up
def is_payfast_ip_address(ip_address_str):
    """
    Return True if ip_address_str matches one of PayFast's server IP addresses.

    Setting: `PAYFAST_IP_ADDRESSES`

    :type ip_address_str: str
    :rtype: bool
    """
    # TODO: Django system check for validity?
    payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
                                   conf.DEFAULT_PAYFAST_IP_ADDRESSES)

    if sys.version_info < (3,):
        # Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
        # (On Python 3, this should generally not happen:
        #  let unexpected bytes values fail as expected.)
        ip_address_str = unicode(ip_address_str)  # noqa: F821
        payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses]  # noqa: F821

    return any(ip_address(ip_address_str) in ip_network(payfast_address)
               for payfast_address in payfast_ip_addresses) 
Example #19
Source File: templates.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example #20
Source File: test_utils.py    From biggraphite with Apache License 2.0 5 votes vote down vote up
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() 
Example #21
Source File: serve_django_app.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)
    #django.core.management.execute_from_command_line(args) 
Example #22
Source File: simpletags.py    From simpleui with MIT License 5 votes vote down vote up
def get_language():
    from django.conf import settings
    return settings.LANGUAGE_CODE.lower() 
Example #23
Source File: simpletags.py    From simpleui with MIT License 5 votes vote down vote up
def __get_config(name):
    from django.conf import settings
    value = os.environ.get(name, getattr(settings, name, None))

    return value 
Example #24
Source File: basehttp.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #25
Source File: run_test.py    From django-pg-partitioning with MIT License 5 votes vote down vote up
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:test@localhost/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_partitioning",
            "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",
                    "class": "logging.StreamHandler",
                    "formatter": "standard"
                }
            },
            "loggers": {
                "pg_partitioning.shortcuts": {
                    "handlers": ["console"],
                    "level": "DEBUG",
                    "propagate": False,
                },
                "pg_partitioning.patch.schema": {
                    "handlers": ["console"],
                    "level": "DEBUG",
                    "propagate": False,
                },
            },
        }
    )

    django.setup() 
Example #26
Source File: render_benchmark.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_django_tests():
    if not django:
        return []

    django.conf.settings.configure()
    django.setup()

    tmpl_src = """
        <table>
            {% for row in table %}
                <tr>
                    {% for column in row.values %}
                        <td>{{ column }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
        </table>
    """
    tmpl_autoescaped_src = ('{% autoescape on %}' +
                            tmpl_src +
                            '{% endautoescape %}')

    tmpl = django.template.Template(tmpl_src)
    tmpl_autoescaped = django.template.Template(tmpl_autoescaped_src)

    tmpl_context = django.template.Context({'table': TABLE_DATA})

    def test_django():
        """Django template"""
        tmpl.render(tmpl_context)

    def test_django_autoescaped():
        """Django template autoescaped"""
        tmpl_autoescaped.render(tmpl_context)

    return [
        test_django,
        test_django_autoescaped,
    ] 
Example #27
Source File: plugin.py    From django_coverage_plugin with Apache License 2.0 5 votes vote down vote up
def check_debug():
    """Check that Django's template debugging is enabled.

    Django's built-in "template debugging" records information the plugin needs
    to do its work.  Check that the setting is correct, and raise an exception
    if it is not.

    Returns True if the debug check was performed, False otherwise
    """
    from django.conf import settings

    if not settings.configured:
        return False

    # I _think_ this check is all that's needed and the 3 "hasattr" checks
    # below can be removed, but it's not clear how to verify that
    from django.apps import apps
    if not apps.ready:
        return False

    # django.template.backends.django gets loaded lazily, so return false
    # until they've been loaded
    if not hasattr(django.template, "backends"):
        return False
    if not hasattr(django.template.backends, "django"):
        return False
    if not hasattr(django.template.backends.django, "DjangoTemplates"):
        raise DjangoTemplatePluginException("Can't use non-Django templates.")

    for engine in django.template.engines.all():
        if not isinstance(engine, django.template.backends.django.DjangoTemplates):
            raise DjangoTemplatePluginException(
                "Can't use non-Django templates."
            )
        if not engine.engine.debug:
            raise DjangoTemplatePluginException(
                "Template debugging must be enabled in settings."
            )

    return True 
Example #28
Source File: runtests.py    From django-translation-manager with Mozilla Public License 2.0 5 votes vote down vote up
def run_tests():
    import django
    from django.test.utils import get_runner
    from django.conf import settings

    django.setup()
    test_runner = get_runner(settings)()
    failures = test_runner.run_tests(["tests"])
    sys.exit(bool(failures)) 
Example #29
Source File: conftest.py    From django-estimators with MIT License 5 votes vote down vote up
def pytest_configure(config):
    # using test version of settings.py
    os.environ['DJANGO_SETTINGS_MODULE'] = "estimators.tests.settings"
    django.setup()

    # set MEDIA_ROOT to temp_dir before starting tests
    from django.conf import settings
    settings.MEDIA_ROOT = temp_dir.name 
Example #30
Source File: admin_interface_tags.py    From django-admin-interface with MIT License 5 votes vote down vote up
def get_admin_interface_languages(context):
    if not settings.USE_I18N:
        # i18n disabled
        return None
    if len(settings.LANGUAGES) < 2:
        # less than 2 languages
        return None
    try:
        set_language_url = reverse('set_language')
    except NoReverseMatch:
        # ImproperlyConfigured - must include i18n urls:
        # urlpatterns += [url(r'^i18n/', include('django.conf.urls.i18n')),]
        return None
    request = context.get('request', None)
    if not request:
        return None
    full_path = request.get_full_path()
    admin_nolang_url = re.sub(r'^\/([\w]{2})([\-\_]{1}[\w]{2})?\/', '/', full_path)
    if admin_nolang_url == full_path:
        # ImproperlyConfigured - must include admin urls using i18n_patterns:
        # from django.conf.urls.i18n import i18n_patterns
        # urlpatterns += i18n_patterns(url(r'^admin/', admin.site.urls))
        return None
    langs_data = []
    default_lang_code = settings.LANGUAGE_CODE
    current_lang_code = translation.get_language() or default_lang_code
    for language in settings.LANGUAGES:
        lang_code = language[0].lower()
        lang_name = language[1].title()
        lang_data = {
            'code': lang_code,
            'name': lang_name,
            'default': lang_code == default_lang_code,
            'active': lang_code == current_lang_code,
            'activation_url': '{}?next=/{}{}'.format(
                set_language_url, lang_code, admin_nolang_url)
        }
        langs_data.append(lang_data)
    return langs_data