Python django.conf() Examples

The following are 30 code examples for showing how to use django.conf(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: django-payfast   Author: PiDelport   File: forms.py    License: 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 2
Project: django-payfast   Author: PiDelport   File: forms.py    License: 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 3
Project: django-usersettings2   Author: mishbahr   File: models.py    License: 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 4
Project: GTDWeb   Author: lanbing510   File: templates.py    License: 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 5
Project: django-cryptography   Author: georgemarshall   File: setup.py    License: 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 6
Project: pwned-passwords-django   Author: ubernostrum   File: runtests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)

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

    django.setup()

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

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 7
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 8
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 9
Project: byro   Author: byro   File: setup.py    License: Apache License 2.0 6 votes vote down vote up
def run(self):
        environ.setdefault("DJANGO_SETTINGS_MODULE", "byro.settings")
        try:
            import django
        except ImportError:  # Move to ModuleNotFoundError once we drop Python 3.5
            return
        django.setup()
        from django.conf import settings
        from django.core import management

        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_OFFLINE = True

        management.call_command("compilemessages", verbosity=1)
        management.call_command("collectstatic", verbosity=1, interactive=False)
        management.call_command("compress", verbosity=1)
        build.run(self) 
Example 10
Project: django-taggit-labels   Author: bennylope   File: conftest.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "test.sqlite3"}
        },
        INSTALLED_APPS=[
            "django.contrib.auth",
            "django.contrib.contenttypes",
            # "django.contrib.sites",
            "taggit",
            "taggit_labels",
            "test_app",
        ],
        MIDDLEWARE_CLASSES=(),
        SITE_ID=1,
    )
    try:
        django.setup()
    except AttributeError:
        # Django 1.7 or lower
        pass 
Example 11
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 12
Project: django-rest-framework-simplejwt   Author: SimpleJWT   File: conf.py    License: MIT License 6 votes vote down vote up
def django_configure():
    from django.conf import settings

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

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

    try:
        import django
        django.setup()
    except AttributeError:
        pass 
Example 13
Project: luscan-devel   Author: blackye   File: templates.py    License: 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 14
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 15
Project: django-calaccess-campaign-browser   Author: california-civic-data-coalition   File: setup.py    License: MIT License 6 votes vote down vote up
def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={
                'default': {
                    'NAME': ':memory:',
                    'ENGINE': 'django.db.backends.sqlite3'
                }
            },
            INSTALLED_APPS=('calaccess_campaign_browser',),
            MIDDLEWARE_CLASSES=()
        )
        from django.core.management import call_command
        import django
        if django.VERSION[:2] >= (1, 7):
            django.setup()
        call_command('test', 'calaccess_campaign_browser') 
Example 16
Project: Dailyfresh-B2C   Author: BeanWei   File: utils.py    License: 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 17
Project: djongo   Author: nesdis   File: tests.py    License: 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 18
Project: maas   Author: maas   File: plugin.py    License: 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 19
Project: django-partial-index   Author: mattiaslinnap   File: migraterunner.py    License: 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 20
Project: django-partial-index   Author: mattiaslinnap   File: runner.py    License: 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 21
Project: django-payfast   Author: PiDelport   File: tests.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        conf.USE_POSTBACK = False
        conf.MERCHANT_ID = '10000100'
        conf.REQUIRE_AMOUNT_MATCH = True

        self.notify_handler_orders = []  # type: list
        payfast.signals.notify.connect(self.notify_handler) 
Example 22
Project: django-payfast   Author: PiDelport   File: forms.py    License: MIT License 5 votes vote down vote up
def full_url(link):
    """
    Return an absolute version of a possibly-relative URL.

    This uses the PAYFAST_URL_BASE setting.
    """
    url_base = (conf.URL_BASE() if callable(conf.URL_BASE) else
                conf.URL_BASE)
    return urljoin(url_base, link) 
Example 23
Project: django-payfast   Author: PiDelport   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_amount_gross(self):
        received = self.cleaned_data['amount_gross']
        if conf.REQUIRE_AMOUNT_MATCH:
            requested = self.instance.amount_gross
            if requested != received:
                raise forms.ValidationError('Amount is not the same: %s != %s' % (
                                            requested, received,))
        return received 
Example 24
Project: GTDWeb   Author: lanbing510   File: makemessages.py    License: GNU General Public License v2.0 5 votes vote down vote up
def copy_plural_forms(self, msgs, locale):
        """
        Copies plural forms header contents from a Django catalog of locale to
        the msgs string, inserting it at the right place. msgs should be the
        contents of a newly created .po file.
        """
        django_dir = os.path.normpath(os.path.join(os.path.dirname(upath(django.__file__))))
        if self.domain == 'djangojs':
            domains = ('djangojs', 'django')
        else:
            domains = ('django',)
        for domain in domains:
            django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
            if os.path.exists(django_po):
                with io.open(django_po, 'r', encoding='utf-8') as fp:
                    m = plural_forms_re.search(fp.read())
                if m:
                    plural_form_line = force_str(m.group('value'))
                    if self.verbosity > 1:
                        self.stdout.write("copying plural forms: %s\n" % plural_form_line)
                    lines = []
                    found = False
                    for line in msgs.split('\n'):
                        if not found and (not line or plural_forms_re.search(line)):
                            line = '%s\n' % plural_form_line
                            found = True
                        lines.append(line)
                    msgs = '\n'.join(lines)
                    break
        return msgs 
Example 25
Project: django-cryptography   Author: georgemarshall   File: setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        if self.verbosity > 0:
            # ensure that deprecation warnings are displayed during testing
            # the following state is assumed:
            # logging.capturewarnings is true
            # a "default" level warnings filter has been added for
            # DeprecationWarning. See django.conf.LazySettings._configure_logging
            logger = logging.getLogger('py.warnings')
            handler = logging.StreamHandler()
            logger.addHandler(handler)
        TestCommand.run(self)
        if self.verbosity > 0:
            # remove the testing-specific handler
            logger.removeHandler(handler) 
Example 26
Project: django-ical   Author: jazzband   File: tests.py    License: MIT License 5 votes vote down vote up
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/
    """

    import django
    from django.conf import settings

    settings.configure(
        DATABASES={
            "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
        },
        INSTALLED_APPS=["django.contrib.contenttypes", "django_ical"],
        MIDDLEWARE_CLASSES=[
            "django.middleware.common.CommonMiddleware",
            "django.contrib.sessions.middleware.SessionMiddleware",
        ],
        SECRET_KEY="snakeoil",
        TIME_ZONE="UTC",
    )

    django.setup()

    from django.test.utils import get_runner

    TestRunner = get_runner(settings)
    test_runner = TestRunner()
    failures = test_runner.run_tests(["django_ical"])
    sys.exit(bool(failures)) 
Example 27
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 28
Project: django-livefield   Author: hearsaycorp   File: setup.py    License: MIT License 5 votes vote down vote up
def run_tests(self):
        from django.conf import settings

        db_engine = os.environ.get('DJANGO_DB_ENGINE', 'sqlite')
        if db_engine == 'mysql':
            db_settings = {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': os.environ['DJANGO_DB_NAME'],
                'USER': os.environ['DJANGO_DB_USER'],
            }
        elif db_engine == 'postgres':
            db_settings = {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': os.environ['DJANGO_DB_NAME'],
                'USER': os.environ['DJANGO_DB_USER'],
            }
        elif db_engine == 'sqlite':
            db_settings = {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(self.DIRNAME, 'database.db'),
            }
        else:
            raise ValueError("Unknown DB engine: %s" % db_engine)

        # Common settings.
        settings.configure(
            DEBUG=True,
            DATABASES={'default': db_settings},
            CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}},
            INSTALLED_APPS=self.APPS)

        import django
        import pytest
        django.setup()
        sys.exit(pytest.main(["tests/"])) 
Example 29
Project: django-subscriptions   Author: kogan   File: migrate.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example 30
Project: django-admin-shell   Author: djk2   File: test_run_code.py    License: MIT License 5 votes vote down vote up
def test_interact_with_env(self):
        """
        Run code having access to something from environ, settings etc.
        Heck if code runing in django environ
        """

        code = "from django.conf import settings\n"
        code += "print(settings.DEBUG)"

        # Default in test DEBUG is False
        result = run_code(code)
        assert result["code"] == code
        assert result["status"] == "success"
        assert result["out"] == "False\n"

        with self.settings(DEBUG=True):
            result = run_code(code)
            assert result["code"] == code
            assert result["status"] == "success"
            assert result["out"] == "True\n"

        code = "from django.conf import settings\n"
        code += "print(settings.SECRET_KEY)"

        result = run_code(code)
        assert result["code"] == code
        assert result["status"] == "success"
        assert result["out"] == "{0}\n".format("x" * 55)

        code = "import django\n"
        code += "print(django.VERSION)"
        result = run_code(code)
        assert result["code"] == code
        assert result["status"] == "success"
        assert result["out"] == "{0}\n".format(str(django.VERSION))