Python django.core.exceptions.ImproperlyConfigured() Examples

The following are 30 code examples for showing how to use django.core.exceptions.ImproperlyConfigured(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

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

Example 1
Project: polls-api   Author: apiaryio   File: urls.py    License: MIT License 6 votes vote down vote up
def healthcheck_view(request):
    content_type = 'application/health+json'
    database_accessible = True

    try:
        connections['default'].cursor()
    except ImproperlyConfigured:
        # Database is not configured (DATABASE_URL may not be set)
        database_accessible = False
    except OperationalError:
        # Database is not accessible
        database_accessible = False

    if database_accessible:
        return JsonResponse({ 'status': 'ok' }, content_type=content_type)

    return JsonResponse({ 'status': 'fail' }, status=503, content_type=content_type) 
Example 2
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: utils.py    License: MIT License 6 votes vote down vote up
def encode_jwt(payload, headers=None):
    """
    :type payload: dict
    :type headers: dict, None
    :rtype: str
    """
    # RS256 in default, because hardcoded legacy
    algorithm = getattr(settings, 'JWT_ENC_ALGORITHM', 'RS256')

    private_key_name = 'JWT_PRIVATE_KEY_{}'.format(payload['iss'].upper())
    private_key = getattr(settings, private_key_name, None)
    if not private_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
            private_key_name))
    encoded = jwt.encode(payload, private_key, algorithm=algorithm,
                         headers=headers)
    return encoded.decode("utf-8") 
Example 3
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: utils.py    License: MIT License 6 votes vote down vote up
def decode_jwt(jwt_value):
    """
    :type jwt_value: str
    """
    try:
        headers_enc, payload_enc, verify_signature = jwt_value.split(".")
    except ValueError:
        raise jwt.InvalidTokenError()

    payload_enc += '=' * (-len(payload_enc) % 4)  # add padding
    payload = json.loads(base64.b64decode(payload_enc).decode("utf-8"))

    algorithms = getattr(settings, 'JWT_JWS_ALGORITHMS', ['HS256', 'RS256'])
    public_key_name = 'JWT_PUBLIC_KEY_{}'.format(payload['iss'].upper())
    public_key = getattr(settings, public_key_name, None)
    if not public_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
                                   public_key_name))

    decoded = jwt.decode(jwt_value, public_key, algorithms=algorithms)
    return decoded 
Example 4
Project: normandy   Author: mozilla   File: checks.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def actions_have_consistent_hashes(app_configs, **kwargs):
    errors = []
    try:
        Action = apps.get_model("recipes", "Action")
        actions = list(Action.objects.filter(implementation__isnull=False))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(Info(f"Could not retrieve actions: {e}", id=INFO_COULD_NOT_RETRIEVE_ACTIONS))
    else:
        for action in actions:
            if action.compute_implementation_hash() != action.implementation_hash:
                msg = "Action '{action}' (id={action.id}) has a mismatched hash".format(
                    action=action
                )
                errors.append(Error(msg, id=ERROR_MISMATCHED_ACTION_HASH))

    return errors 
Example 5
Project: normandy   Author: mozilla   File: models.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def update_signature(self):
        try:
            autographer = Autographer()
        except ImproperlyConfigured:
            self.signature = None
            return

        # Don't sign recipe that aren't enabled
        if not (self.approved_revision and self.approved_revision.enabled):
            return

        logger.info(
            f"Requesting signature for recipe with id {self.id} from Autograph",
            extra={"code": INFO_REQUESTING_RECIPE_SIGNATURES, "recipe_ids": [self.id]},
        )

        signature_data = autographer.sign_data([self.canonical_json()])[0]
        signature = Signature(**signature_data)
        signature.save()
        self.signature = signature 
Example 6
Project: normandy   Author: mozilla   File: models.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def update_signature(self):
        try:
            autographer = Autographer()
        except ImproperlyConfigured:
            self.signature = None
            return

        logger.info(
            f"Requesting signature for action named {self.name} from Autograph",
            extra={"code": INFO_REQUESTING_ACTION_SIGNATURES, "action_names": [self.name]},
        )

        signature_data = autographer.sign_data([self.canonical_json()])[0]
        signature = Signature(**signature_data)
        signature.save()
        self.signature = signature 
Example 7
Project: django-phone-verify   Author: CuriousLearner   File: services.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _check_required_settings(self):
        required_settings = {
            "BACKEND",
            "OPTIONS",
            "TOKEN_LENGTH",
            "MESSAGE",
            "APP_NAME",
            "SECURITY_CODE_EXPIRATION_TIME",
            "VERIFY_SECURITY_CODE_ONLY_ONCE",
        }
        user_settings = set(settings.PHONE_VERIFICATION.keys())
        if not required_settings.issubset(user_settings):
            raise ImproperlyConfigured(
                "Please specify following settings in settings.py: {}".format(
                    ", ".join(required_settings - user_settings)
                )
            ) 
Example 8
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 9
Project: django-usersettings2   Author: mishbahr   File: shortcuts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_usersettings_model():
    """
    Returns the ``UserSettings`` model that is active in this project.
    """
    try:
        from django.apps import apps
        get_model = apps.get_model
    except ImportError:
        from django.db.models.loading import get_model

    try:
        app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
    except ValueError:
        raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the '
                                   'form "app_label.model_name"')
    usersettings_model = get_model(app_label, model_name)
    if usersettings_model is None:
        raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has '
                                   'not been installed' % settings.USERSETTINGS_MODEL)
    return usersettings_model 
Example 10
Project: StormOnline   Author: stormsha   File: sites.py    License: Apache License 2.0 6 votes vote down vote up
def check_dependencies(self):
        """
        Check that all things needed to run the admin have been correctly installed.

        The default implementation checks that LogEntry, ContentType and the
        auth context processor are installed.
        """
        from django.contrib.contenttypes.models import ContentType

        if not ContentType._meta.installed:
            raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
                                       "your INSTALLED_APPS setting in order to use the admin application.")

        default_template_engine = Engine.get_default()
        if not ('django.contrib.auth.context_processors.auth' in default_template_engine.context_processors or
                'django.core.context_processors.auth' in default_template_engine.context_processors):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.") 
Example 11
Project: GTDWeb   Author: lanbing510   File: list.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if render_to_response is overridden.
        """
        try:
            names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
        except ImproperlyConfigured:
            # If template_name isn't specified, it's not a problem --
            # we just start with an empty list.
            names = []

        # If the list is a queryset, we'll invent a template name based on the
        # app and model name. This name gets put at the end of the template
        # name list so that user-supplied names override the automatically-
        # generated ones.
        if hasattr(self.object_list, 'model'):
            opts = self.object_list.model._meta
            names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))

        return names 
Example 12
Project: GTDWeb   Author: lanbing510   File: detail.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_queryset(self):
        """
        Return the `QuerySet` that will be used to look up the object.

        Note that this method is called by the default implementation of
        `get_object` and may not be called if `get_object` is overridden.
        """
        if self.queryset is None:
            if self.model:
                return self.model._default_manager.all()
            else:
                raise ImproperlyConfigured(
                    "%(cls)s is missing a QuerySet. Define "
                    "%(cls)s.model, %(cls)s.queryset, or override "
                    "%(cls)s.get_queryset()." % {
                        'cls': self.__class__.__name__
                    }
                )
        return self.queryset.all() 
Example 13
Project: GTDWeb   Author: lanbing510   File: edit.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_success_url(self):
        """
        Returns the supplied URL.
        """
        if self.success_url:
            # force_text can be removed with deprecation warning
            self.success_url = force_text(self.success_url)
            if PERCENT_PLACEHOLDER_REGEX.search(self.success_url):
                warnings.warn(
                    "%()s placeholder style in success_url is deprecated. "
                    "Please replace them by the {} Python format syntax.",
                    RemovedInDjango110Warning, stacklevel=2
                )
                url = self.success_url % self.object.__dict__
            else:
                url = self.success_url.format(**self.object.__dict__)
        else:
            try:
                url = self.object.get_absolute_url()
            except AttributeError:
                raise ImproperlyConfigured(
                    "No URL to redirect to.  Either provide a url or define"
                    " a get_absolute_url method on the Model.")
        return url 
Example 14
Project: GTDWeb   Author: lanbing510   File: edit.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_success_url(self):
        if self.success_url:
            # force_text can be removed with deprecation warning
            self.success_url = force_text(self.success_url)
            if PERCENT_PLACEHOLDER_REGEX.search(self.success_url):
                warnings.warn(
                    "%()s placeholder style in success_url is deprecated. "
                    "Please replace them by the {} Python format syntax.",
                    RemovedInDjango110Warning, stacklevel=2
                )
                return self.success_url % self.object.__dict__
            else:
                return self.success_url.format(**self.object.__dict__)
        else:
            raise ImproperlyConfigured(
                "No URL to redirect to. Provide a success_url.") 
Example 15
Project: GTDWeb   Author: lanbing510   File: module_loading.py    License: GNU General Public License v2.0 6 votes vote down vote up
def import_by_path(dotted_path, error_prefix=''):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImproperlyConfigured if something goes wrong.
    """
    warnings.warn(
        'import_by_path() has been deprecated. Use import_string() instead.',
        RemovedInDjango19Warning, stacklevel=2)
    try:
        attr = import_string(dotted_path)
    except ImportError as e:
        msg = '%sError importing module %s: "%s"' % (
            error_prefix, dotted_path, e)
        six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
                    sys.exc_info()[2])
    return attr 
Example 16
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def load_backend(backend_name):
    # Look for a fully qualified database backend name
    try:
        return import_module('%s.base' % backend_name)
    except ImportError as e_user:
        # The database backend wasn't found. Display a helpful error message
        # listing all possible (built-in) database backends.
        backend_dir = os.path.join(os.path.dirname(upath(__file__)), 'backends')
        try:
            builtin_backends = [
                name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
                if ispkg and name != 'dummy']
        except EnvironmentError:
            builtin_backends = []
        if backend_name not in ['django.db.backends.%s' % b for b in
                                builtin_backends]:
            backend_reprs = map(repr, sorted(builtin_backends))
            error_msg = ("%r isn't an available database backend.\n"
                         "Try using 'django.db.backends.XXX', where XXX "
                         "is one of:\n    %s\nError was: %s" %
                         (backend_name, ", ".join(backend_reprs), e_user))
            raise ImproperlyConfigured(error_msg)
        else:
            # If there's some other error, this must be an error in Django
            raise 
Example 17
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_connection_params(self):
        settings_dict = self.settings_dict
        # None may be used to connect to the default 'postgres' db
        if settings_dict['NAME'] == '':
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply the NAME value.")
        conn_params = {
            'database': settings_dict['NAME'] or 'postgres',
        }
        conn_params.update(settings_dict['OPTIONS'])
        conn_params.pop('isolation_level', None)
        if settings_dict['USER']:
            conn_params['user'] = settings_dict['USER']
        if settings_dict['PASSWORD']:
            conn_params['password'] = force_str(settings_dict['PASSWORD'])
        if settings_dict['HOST']:
            conn_params['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            conn_params['port'] = settings_dict['PORT']
        return conn_params 
Example 18
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _setup_environment(environ):
    # Cygwin requires some special voodoo to set the environment variables
    # properly so that Oracle will see them.
    if platform.system().upper().startswith('CYGWIN'):
        try:
            import ctypes
        except ImportError as e:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured("Error loading ctypes: %s; "
                                       "the Oracle backend requires ctypes to "
                                       "operate correctly under Cygwin." % e)
        kernel32 = ctypes.CDLL('kernel32')
        for name, value in environ:
            kernel32.SetEnvironmentVariableA(name, value)
    else:
        os.environ.update(environ) 
Example 19
Project: django-rest-polymorphic   Author: apirobot   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_model_serializer_mapping_is_none(self):
        class EmptyPolymorphicSerializer(PolymorphicSerializer):
            pass

        with pytest.raises(ImproperlyConfigured) as excinfo:
            EmptyPolymorphicSerializer()

        assert str(excinfo.value) == (
            '`EmptyPolymorphicSerializer` is missing a '
            '`EmptyPolymorphicSerializer.model_serializer_mapping` attribute'
        ) 
Example 20
Project: django-rest-polymorphic   Author: apirobot   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_resource_type_field_name_is_not_string(self, mocker):
        class NotStringPolymorphicSerializer(PolymorphicSerializer):
            model_serializer_mapping = mocker.MagicMock
            resource_type_field_name = 1

        with pytest.raises(ImproperlyConfigured) as excinfo:
            NotStringPolymorphicSerializer()

        assert str(excinfo.value) == (
            '`NotStringPolymorphicSerializer.resource_type_field_name` must '
            'be a string'
        ) 
Example 21
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    License: MIT License 5 votes vote down vote up
def __new__(cls, *args, **kwargs):
        if cls.model_serializer_mapping is None:
            raise ImproperlyConfigured(
                '`{cls}` is missing a '
                '`{cls}.model_serializer_mapping` attribute'.format(
                    cls=cls.__name__
                )
            )
        if not isinstance(cls.resource_type_field_name, string_types):
            raise ImproperlyConfigured(
                '`{cls}.resource_type_field_name` must be a string'.format(
                    cls=cls.__name__
                )
            )
        return super(PolymorphicSerializer, cls).__new__(cls, *args, **kwargs) 
Example 22
Project: django-template   Author: liip   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_env_variable(var_name, default=None):
    """
    Get the environment variable or return exception
    """
    try:
        return os.environ[var_name]
    except KeyError:
        if default is not None:
            return default
        else:
            error_msg = "Set the %s environment variable" % var_name
            raise ImproperlyConfigured(error_msg) 
Example 23
Project: pinax-documents   Author: pinax   File: conf.py    License: MIT License 5 votes vote down vote up
def load_path_attr(path):
    i = path.rfind(".")
    module, attr = path[:i], path[i + 1:]
    try:
        mod = importlib.import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured(f"Error importing {module}: '{e}'")
    try:
        attr = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured(f"Module '{module}' does not define a '{attr}'")
    return attr 
Example 24
Project: django-places   Author: oscarmcm   File: conf.py    License: MIT License 5 votes vote down vote up
def __init__(self, django_settings):
        self.django_settings = django_settings

        for setting in self.required_settings:
            prefixed_name = '%s_%s' % (self.prefix, setting)
            if not hasattr(self.django_settings, prefixed_name):
                raise ImproperlyConfigured(
                    "The '%s' setting is required." % prefixed_name
                ) 
Example 25
def init_config(self, request, app_list):
        self.request = request
        self.app_list = app_list

        self.config = getattr(settings, 'ADMIN_REORDER', None)
        if not self.config:
            # ADMIN_REORDER settings is not defined.
            raise ImproperlyConfigured('ADMIN_REORDER config is not defined.')

        if not isinstance(self.config, (tuple, list)):
            raise ImproperlyConfigured(
                'ADMIN_REORDER config parameter must be tuple or list. '
                'Got {config}'.format(config=self.config))

        admin_index = admin.site.index(request)
        try:
            # try to get all installed models
            app_list = admin_index.context_data['app_list']
        except KeyError:
            # use app_list from context if this fails
            pass

        # Flatten all models from apps
        self.models_list = []
        for app in app_list:
            for model in app['models']:
                model['model_name'] = self.get_model_name(
                    app['app_label'], model['object_name'])
                self.models_list.append(model) 
Example 26
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: test_utils.py    License: MIT License 5 votes vote down vote up
def test_encode_jwt_no_private_key_in_setting(self):
        payload = self._get_payload()
        self.assertRaises(ImproperlyConfigured,
                          utils.encode_jwt, payload) 
Example 27
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: test_utils.py    License: MIT License 5 votes vote down vote up
def test_decode_jwt_public_key_not_found(self):
        payload = self._get_payload()
        jwt_value = utils.encode_jwt(payload)
        self.assertRaises(ImproperlyConfigured, utils.decode_jwt,
                          jwt_value) 
Example 28
Project: normandy   Author: mozilla   File: metrics.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, options):
        super().__init__(options)
        if not settings.DEBUG:
            raise ImproperlyConfigured(
                f"The {self.__class__.__name} can only be used if DEBUG=True"
            ) 
Example 29
Project: normandy   Author: mozilla   File: signing.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def check_config(self):
        required_keys = ["URL", "HAWK_ID", "HAWK_SECRET_KEY"]
        for key in required_keys:
            if getattr(settings, "AUTOGRAPH_" + key) is None:
                msg = "set settings.AUTOGRAPH_{} to use action signatures".format(key)
                raise ImproperlyConfigured(msg) 
Example 30
Project: normandy   Author: mozilla   File: checks.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def recipe_signatures_are_correct(app_configs, **kwargs):
    errors = []
    try:
        Recipe = apps.get_model("recipes", "Recipe")
        # pre-fetch signatures, to avoid race condition with deleted signatures
        signed_recipes = list(Recipe.objects.exclude(signature=None).select_related("signature"))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(Info(f"Could not retrieve recipes: {e}", id=INFO_COULD_NOT_RETRIEVE_RECIPES))
        return errors

    try:
        for recipe in signed_recipes:
            data = recipe.canonical_json()
            signature = recipe.signature.signature
            pubkey = recipe.signature.public_key
            x5u = recipe.signature.x5u
            try:
                if x5u:
                    signing.verify_signature_x5u(data, signature, x5u)
                else:
                    signing.verify_signature_pubkey(data, signature, pubkey)
            except signing.BadSignature as e:
                msg = "Recipe '{recipe}' (id={recipe.id}) has a bad signature: {detail}".format(
                    recipe=recipe, detail=e.detail
                )
                errors.append(Error(msg, id=ERROR_INVALID_RECIPE_SIGNATURE))
            except requests.RequestException as exc:
                msg = (
                    f"The signature for recipe with ID {recipe.id} could not be be verified due to "
                    f"network error when requesting the url {x5u!r}. {exc}"
                )
                errors.append(Error(msg, id=ERROR_COULD_NOT_VERIFY_CERTIFICATE))
    except (ProgrammingError, OperationalError, ImproperlyConfigured) as e:
        errors.append(
            Warning(f"Could not check signatures: {e}", id=WARNING_COULD_NOT_CHECK_SIGNATURES)
        )

    return errors