当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ImproperlyConfigured方法代码示例

本文整理汇总了Python中django.core.exceptions.ImproperlyConfigured方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ImproperlyConfigured方法的具体用法?Python exceptions.ImproperlyConfigured怎么用?Python exceptions.ImproperlyConfigured使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.exceptions的用法示例。


在下文中一共展示了exceptions.ImproperlyConfigured方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: healthcheck_view

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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) 
开发者ID:apiaryio,项目名称:polls-api,代码行数:19,代码来源:urls.py

示例2: encode_jwt

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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") 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:19,代码来源:utils.py

示例3: decode_jwt

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:23,代码来源:utils.py

示例4: actions_have_consistent_hashes

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:mozilla,项目名称:normandy,代码行数:18,代码来源:checks.py

示例5: update_signature

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:mozilla,项目名称:normandy,代码行数:22,代码来源:models.py

示例6: _check_required_settings

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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)
                )
            ) 
开发者ID:CuriousLearner,项目名称:django-phone-verify,代码行数:19,代码来源:services.py

示例7: get_current

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:mishbahr,项目名称:django-usersettings2,代码行数:23,代码来源:models.py

示例8: get_usersettings_model

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:mishbahr,项目名称:django-usersettings2,代码行数:22,代码来源:shortcuts.py

示例9: check_dependencies

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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.") 
开发者ID:stormsha,项目名称:StormOnline,代码行数:20,代码来源:sites.py

示例10: get_template_names

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:list.py

示例11: get_queryset

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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() 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:detail.py

示例12: get_success_url

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:26,代码来源:edit.py

示例13: import_by_path

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:module_loading.py

示例14: load_backend

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:27,代码来源:utils.py

示例15: get_connection_params

# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ImproperlyConfigured [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:24,代码来源:base.py


注:本文中的django.core.exceptions.ImproperlyConfigured方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。