Python django.core.exceptions 模块,ImproperlyConfigured() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.exceptions.ImproperlyConfigured()

项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __init__(self, app_names=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = OrderedDict()
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            raise ImproperlyConfigured(
                "Your STATICFILES_DIRS setting is not a tuple or list; "
                "perhaps you forgot a trailing comma?")
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                prefix, root = root
            else:
                prefix = ''
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                raise ImproperlyConfigured(
                    "The STATICFILES_DIRS setting should "
                    "not contain the STATIC_ROOT setting")
            if (prefix, root) not in self.locations:
                self.locations.append((prefix, root))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage
        super(FileSystemFinder, self).__init__(*args, **kwargs)
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def get_class(import_path=None):
    """
    Largely based on django.core.files.storage's get_storage_class
    """
    from django.core.exceptions import ImproperlyConfigured
    if import_path is None:
        raise ImproperlyConfigured('No class path specified.')
    try:
        dot = import_path.rindex('.')
    except ValueError:
        raise ImproperlyConfigured("%s isn't a module." % import_path)
    module, classname = import_path[:dot], import_path[dot+1:]
    try:
        mod = import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e))
    try:
        return getattr(mod, classname)
    except AttributeError:
        raise ImproperlyConfigured('Module "%s" does not define a "%s" class.' % (module, classname))
项目:cmsplugin-form-handler    作者:mkoistinen    | 项目源码 | 文件源码
def test_non_existent_plugin_submission(self):
        """
        Test that a submitting a form for a non-existent plugin meets
        defined behavior.
        """
        sample_name = self.get_random_string(10)
        sample_msg = self.get_random_string(100)

        # Get non-existent plugin ID:
        bad_id = CMSPlugin.objects.aggregate(max=Max('id'))['max'] + 1
        assert bad_id

        action_url = reverse(
            'cmsplugin_form_handler:process_form',
            args=(bad_id + 1, )
        )

        with self.assertRaises(ImproperlyConfigured):
            self.client.post(action_url, {
                'name': sample_name,
                'message': sample_msg,
                'cmsplugin_form_source_url': '/en/',
            }, follow=True)
项目:cmsplugin-form-handler    作者:mkoistinen    | 项目源码 | 文件源码
def test_non_form_handler_plugin(self):
        """
        Test that attempting to submit a non-cmsplugin-form-handler plugin
        fails as expected
        """
        sample_name = self.get_random_string(10)
        sample_msg = self.get_random_string(100)

        action_url = reverse(
            'cmsplugin_form_handler:process_form',
            args=(self.text_plugin, )
        )

        with self.assertRaises(ImproperlyConfigured):
            self.client.post(action_url, {
                'name': sample_name,
                'message': sample_msg,
                'cmsplugin_form_source_url': '/en/',
            }, follow=True)
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def _get_oauth2_client_id_and_secret(settings_instance):
    """Initializes client id and client secret based on the settings"""
    secret_json = getattr(django.conf.settings,
                          'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
    if secret_json is not None:
        return _load_client_secrets(secret_json)
    else:
        client_id = getattr(settings_instance, "GOOGLE_OAUTH2_CLIENT_ID",
                            None)
        client_secret = getattr(settings_instance,
                                "GOOGLE_OAUTH2_CLIENT_SECRET", None)
        if client_id is not None and client_secret is not None:
            return client_id, client_secret
        else:
            raise exceptions.ImproperlyConfigured(
                "Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or  "
                " both GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET "
                "in settings.py")
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
def __init__(self, settings_instance):
        self.scopes = getattr(settings_instance, 'GOOGLE_OAUTH2_SCOPES',
                              GOOGLE_OAUTH2_DEFAULT_SCOPES)
        self.request_prefix = getattr(settings_instance,
                                      'GOOGLE_OAUTH2_REQUEST_ATTRIBUTE',
                                      GOOGLE_OAUTH2_REQUEST_ATTRIBUTE)
        self.client_id, self.client_secret = \
            _get_oauth2_client_id_and_secret(settings_instance)

        if ('django.contrib.sessions.middleware.SessionMiddleware'
                not in settings_instance.MIDDLEWARE_CLASSES):
            raise exceptions.ImproperlyConfigured(
                "The Google OAuth2 Helper requires session middleware to "
                "be installed. Edit your MIDDLEWARE_CLASSES setting"
                " to include 'django.contrib.sessions.middleware."
                "SessionMiddleware'.")
项目:django-elasticsearch-dsl-drf    作者:barseghyanartur    | 项目源码 | 文件源码
def __init__(self, instance=None, data=empty, **kwargs):
        super(DocumentSerializer, self).__init__(instance, data, **kwargs)

        if not hasattr(self.Meta, 'document') or self.Meta.document is None:
            raise ImproperlyConfigured(
                "You must set the 'document' attribute on the serializer "
                "Meta class."
            )

        if not issubclass(self.Meta.document, (DocType,)):
            raise ImproperlyConfigured(
                "You must subclass the serializer 'document' from the DocType"
                "class."
            )

        if not self.instance:
            self.instance = EmptySearch()
项目:minimum-entropy    作者:DistrictDataLabs    | 项目源码 | 文件源码
def environ_setting(name, default=None):
    """
    Fetch setting from the environment- if not found, then this setting is
    ImproperlyConfigured.
    """
    if name not in os.environ and default is None:
        from django.core.exceptions import ImproperlyConfigured
        raise ImproperlyConfigured(
            "The {0} ENVVAR is not set.".format(name)
        )

    return os.environ.get(name, default)


##########################################################################
## Build Paths inside of project with os.path.join
##########################################################################

## Project is the location of the minent directory (with the wsgi.py)
## Note that BASE_DIR (originally in this file) is the same as Project
## Repository is the location of the project and the apps and other files
项目:django-ajax-views    作者:Pyco7    | 项目源码 | 文件源码
def ajax_filter(self, opts, *args, **kwargs):
        # args = set()
        # args.update((Q(field__isnull=True) | Q(field__name='none'),))
        filter_field = opts.get('filter_field', None)
        if isinstance(filter_field, tuple) and len(filter_field) == 2 and \
           (filter_field[1] == 'exclude' or filter_field[1] == 'exclude_filter'):
            return self.filter(*args, **kwargs)

        if opts.get('selected_filter_index', -1) >= 0 and opts.get('selected_filter_values', None):
            filter_field = opts['filter_field']
            if isinstance(filter_field, str):
                kwargs[filter_field + '__in'] = opts['selected_filter_values']
            elif isinstance(filter_field, tuple) and len(filter_field) == 3:
                kwargs[filter_field[0] + '__in'] = opts['selected_filter_values']
            elif isinstance(filter_field, tuple) and len(filter_field) == 2 and filter_field[1] == 'date':
                if opts['selected_filter_values'].get('min_date', None):
                    kwargs[filter_field[0] + '__gte'] = parse(opts['selected_filter_values']['min_date']).date()
                if opts['selected_filter_values'].get('max_date', None):
                    kwargs[filter_field[0] + '__lte'] = parse(opts['selected_filter_values']['max_date']).date()
            else:
                raise ImproperlyConfigured('filter field attribute needs to be a string or tuple.')

        if self.distinct_qs:
            return self.filter(*args, **kwargs).distinct()
        return self.filter(*args, **kwargs)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def regex(self):
        """
        Returns a compiled regular expression, depending upon the activated
        language-code.
        """
        language_code = get_language()
        if language_code not in self._regex_dict:
            if isinstance(self._regex, six.string_types):
                regex = self._regex
            else:
                regex = force_text(self._regex)
            try:
                compiled_regex = re.compile(regex, re.UNICODE)
            except re.error as e:
                raise ImproperlyConfigured(
                    '"%s" is not a valid regular expression: %s' %
                    (regex, six.text_type(e)))

            self._regex_dict[language_code] = compiled_regex
        return self._regex_dict[language_code]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def check_migrations(self):
        """
        Checks to see if the set of migrations on disk matches the
        migrations in the database. Prints a warning if they don't match.
        """
        try:
            executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
        except ImproperlyConfigured:
            # No databases are configured (or the dummy one)
            return
        except MigrationSchemaMissing:
            self.stdout.write(self.style.NOTICE(
                "\nNot checking migrations as it is not possible to access/create the django_migrations table."
            ))
            return

        plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
        if plan:
            self.stdout.write(self.style.NOTICE(
                "\nYou have unapplied migrations; your app may not work properly until they are applied."
            ))
            self.stdout.write(self.style.NOTICE("Run 'python manage.py migrate' to apply them.\n"))

# Kept for backward compatibility
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _get_storage_path(cls):
        try:
            return cls._storage_path
        except AttributeError:
            storage_path = getattr(settings, "SESSION_FILE_PATH", None)
            if not storage_path:
                storage_path = tempfile.gettempdir()

            # Make sure the storage path is valid.
            if not os.path.isdir(storage_path):
                raise ImproperlyConfigured(
                    "The session storage path %r doesn't exist. Please set your"
                    " SESSION_FILE_PATH setting to an existing directory in which"
                    " Django can store session data." % storage_path)

            cls._storage_path = storage_path
            return storage_path
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_current(self, request=None):
        """
        Returns the current Site based on the SITE_ID in the project's settings.
        If SITE_ID isn't defined, it returns the site with domain matching
        request.get_host(). The ``Site`` object is cached the first time it's
        retrieved from the database.
        """
        from django.conf import settings
        if getattr(settings, 'SITE_ID', ''):
            site_id = settings.SITE_ID
            return self._get_site_by_id(site_id)
        elif request:
            return self._get_site_by_request(request)

        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 or pass a request to "
            "Site.objects.get_current() to fix this error."
        )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def check_settings(base_url=None):
    """
    Checks if the staticfiles settings have sane values.
    """
    if base_url is None:
        base_url = settings.STATIC_URL
    if not base_url:
        raise ImproperlyConfigured(
            "You're using the staticfiles app "
            "without having set the required STATIC_URL setting.")
    if settings.MEDIA_URL == base_url:
        raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
                                   "settings must have different values")
    if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
            (settings.MEDIA_ROOT == settings.STATIC_ROOT)):
        raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
                                   "settings must have different values")
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_new_connection(self, conn_params):
        conn = super(DatabaseWrapper, self).get_new_connection(conn_params)
        # Enabling extension loading on the SQLite connection.
        try:
            conn.enable_load_extension(True)
        except AttributeError:
            raise ImproperlyConfigured(
                'The pysqlite library does not support C extension loading. '
                'Both SQLite and pysqlite must be configured to allow '
                'the loading of extensions to use SpatiaLite.')
        # Loading the SpatiaLite library extension on the connection, and returning
        # the created cursor.
        cur = conn.cursor(factory=SQLiteCursorWrapper)
        try:
            cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
        except Exception as msg:
            new_msg = (
                'Unable to load the SpatiaLite library extension '
                '"%s" because: %s') % (self.spatialite_lib, msg)
            six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
        cur.close()
        return conn
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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'] == '':
            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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def prepare_sql_script(self, sql):
        """
        Takes an SQL script that may contain multiple lines and returns a list
        of statements to feed to successive cursor.execute() calls.

        Since few databases are able to process raw SQL scripts in a single
        cursor.execute() call and PEP 249 doesn't talk about this use case,
        the default implementation is conservative.
        """
        try:
            import sqlparse
        except ImportError:
            raise ImproperlyConfigured(
                "sqlparse is required if you don't split your SQL "
                "statements manually."
            )
        else:
            return [sqlparse.format(statement, strip_comments=True)
                    for statement in sqlparse.split(sql) if statement]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def find_template_loader(self, loader):
        if isinstance(loader, (tuple, list)):
            args = list(loader[1:])
            loader = loader[0]
        else:
            args = []

        if isinstance(loader, six.string_types):
            loader_class = import_string(loader)

            if getattr(loader_class, '_accepts_engine_in_init', False):
                args.insert(0, self)
            else:
                warnings.warn(
                    "%s inherits from django.template.loader.BaseLoader "
                    "instead of django.template.loaders.base.Loader. " %
                    loader, RemovedInDjango110Warning, stacklevel=2)

            return loader_class(*args)
        else:
            raise ImproperlyConfigured(
                "Invalid value in template loaders configuration: %r" % loader)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def static(prefix, view=serve, **kwargs):
    """
    Helper function to return a URL pattern for serving files in debug mode.

    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    """
    # No-op if not in debug mode or an non-local prefix
    if not settings.DEBUG or (prefix and '://' in prefix):
        return []
    elif not prefix:
        raise ImproperlyConfigured("Empty static prefix not permitted")
    return [
        url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
    ]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def url(regex, view, kwargs=None, name=None, prefix=''):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    else:
        if isinstance(view, six.string_types):
            warnings.warn(
                'Support for string view arguments to url() is deprecated and '
                'will be removed in Django 1.10 (got %s). Pass the callable '
                'instead.' % view,
                RemovedInDjango110Warning, stacklevel=2
            )
            if not view:
                raise ImproperlyConfigured('Empty URL pattern view name not permitted (for pattern %r)' % regex)
            if prefix:
                view = prefix + '.' + view
        return RegexURLPattern(regex, view, kwargs, name)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _setup(self, name=None):
        """
        Load the settings module pointed to by the environment variable. This
        is used the first time we need any settings at all, if the user has not
        previously configured the settings manually.
        """
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ("setting %s" % name) if name else "settings"
            raise ImproperlyConfigured(
                "Requested %s, but settings are not configured. "
                "You must either define the environment variable %s "
                "or call settings.configure() before accessing settings."
                % (desc, ENVIRONMENT_VARIABLE))

        self._wrapped = Settings(settings_module)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _get_storage_path(cls):
        try:
            return cls._storage_path
        except AttributeError:
            storage_path = getattr(settings, "SESSION_FILE_PATH", None)
            if not storage_path:
                storage_path = tempfile.gettempdir()

            # Make sure the storage path is valid.
            if not os.path.isdir(storage_path):
                raise ImproperlyConfigured(
                    "The session storage path %r doesn't exist. Please set your"
                    " SESSION_FILE_PATH setting to an existing directory in which"
                    " Django can store session data." % storage_path)

            cls._storage_path = storage_path
            return storage_path
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def get_current(self, request=None):
        """
        Returns the current Site based on the SITE_ID in the project's settings.
        If SITE_ID isn't defined, it returns the site with domain matching
        request.get_host(). The ``Site`` object is cached the first time it's
        retrieved from the database.
        """
        from django.conf import settings
        if getattr(settings, 'SITE_ID', ''):
            site_id = settings.SITE_ID
            return self._get_site_by_id(site_id)
        elif request:
            return self._get_site_by_request(request)

        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 or pass a request to "
            "Site.objects.get_current() to fix this error."
        )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __init__(self, app_names=None, *args, **kwargs):
        # List of locations with static files
        self.locations = []
        # Maps dir paths to an appropriate storage instance
        self.storages = OrderedDict()
        if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
            raise ImproperlyConfigured(
                "Your STATICFILES_DIRS setting is not a tuple or list; "
                "perhaps you forgot a trailing comma?")
        for root in settings.STATICFILES_DIRS:
            if isinstance(root, (list, tuple)):
                prefix, root = root
            else:
                prefix = ''
            if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
                raise ImproperlyConfigured(
                    "The STATICFILES_DIRS setting should "
                    "not contain the STATIC_ROOT setting")
            if (prefix, root) not in self.locations:
                self.locations.append((prefix, root))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage
        super(FileSystemFinder, self).__init__(*args, **kwargs)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        # Before we get too far, make sure pysqlite 2.5+ is installed.
        if Database.version_info < (2, 5, 0):
            raise ImproperlyConfigured('Only versions of pysqlite 2.5+ are '
                                       'compatible with SpatiaLite and GeoDjango.')

        # Trying to find the location of the SpatiaLite library.
        # Here we are figuring out the path to the SpatiaLite library
        # (`libspatialite`). If it's not in the system library path (e.g., it
        # cannot be found by `ctypes.util.find_library`), then it may be set
        # manually in the settings via the `SPATIALITE_LIBRARY_PATH` setting.
        self.spatialite_lib = getattr(settings, 'SPATIALITE_LIBRARY_PATH',
                                      find_library('spatialite'))
        if not self.spatialite_lib:
            raise ImproperlyConfigured('Unable to locate the SpatiaLite library. '
                                       'Make sure it is in your library path, or set '
                                       'SPATIALITE_LIBRARY_PATH in your settings.'
                                       )
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.features = DatabaseFeatures(self)
        self.ops = SpatiaLiteOperations(self)
        self.client = SpatiaLiteClient(self)
        self.introspection = SpatiaLiteIntrospection(self)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def get_new_connection(self, conn_params):
        conn = super(DatabaseWrapper, self).get_new_connection(conn_params)
        # Enabling extension loading on the SQLite connection.
        try:
            conn.enable_load_extension(True)
        except AttributeError:
            raise ImproperlyConfigured(
                'The pysqlite library does not support C extension loading. '
                'Both SQLite and pysqlite must be configured to allow '
                'the loading of extensions to use SpatiaLite.')
        # Loading the SpatiaLite library extension on the connection, and returning
        # the created cursor.
        cur = conn.cursor(factory=SQLiteCursorWrapper)
        try:
            cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
        except Exception as msg:
            new_msg = (
                'Unable to load the SpatiaLite library extension '
                '"%s" because: %s') % (self.spatialite_lib, msg)
            six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
        cur.close()
        return conn
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def formfield_for_dbfield(self, db_field, request, **kwargs):
        """
        Overloaded from ModelAdmin so that an OpenLayersWidget is used
        for viewing/editing 2D GeometryFields (OpenLayers 2 does not support
        3D editing).
        """
        if isinstance(db_field, models.GeometryField) and db_field.dim < 3:
            if not HAS_GDAL and db_field.srid != self.map_srid:
                raise ImproperlyConfigured(
                    "Map SRID is %s and SRID of `%s` is %s. GDAL must be "
                    "installed to perform the transformation."
                    % (self.map_srid, db_field, db_field.srid)
                )
            # Setting the widget with the newly defined widget.
            kwargs['widget'] = self.get_map_widget(db_field)
            return db_field.formfield(**kwargs)
        else:
            return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_translate_model_with_existing_field(self):
        class TestModel2(models.Model):
            title = models.CharField(max_length=100)
            title_nl = models.CharField(max_length=100)

            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        expected_message = (
            'Error adding translation field. Model "TestModel2" already '
            'contains a field named "title_nl".'
        )

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(TestModel2)
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def get_available_languages_setting():
    '''
    list of available languages for modeltrans translations.
    defaults to the list of language codes extracted from django setting LANGUAGES
    '''
    languages = tuple(set(getattr(
        settings,
        'MODELTRANS_AVAILABLE_LANGUAGES',
        (code for code, _ in getattr(settings, 'LANGUAGES'))
    )))

    if not all(isinstance(x, six.string_types) for x in languages):
        raise ImproperlyConfigured('MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings')

    # make sure LANGUAGE_CODE is not in available languages
    return (lang for lang in languages if lang != get_default_language())
项目:django-tree    作者:BertrandBordage    | 项目源码 | 文件源码
def __init__(self, model_lookup, path_field='path', parent_field='parent',
                 order_by=None, max_siblings=DEFAULT_MAX_SIBLINGS):
        self.model_lookup = model_lookup
        self.path_field = path_field
        self.parent_field = parent_field
        if path_field in order_by:
            raise ImproperlyConfigured(
                'Cannot use `%s` in `CreateTreeTrigger.order_by`.'
                % path_field)
        self.order_by = () if order_by is None else tuple(order_by)
        if not (isinstance(max_siblings, int) and max_siblings > 0):
            raise ImproperlyConfigured(
                '`max_siblings` must be a positive integer, not %s.'
                % repr(max_siblings))
        self.max_siblings = max_siblings
        i = self.max_siblings
        n = 0
        while i > 1.0:
            i /= ALPHANUM_LEN
            n += 1
        self.label_size = n
项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_cache(cache=None):
    """Return ``cache`` or the 'default' cache if ``cache`` is not specified or
    ``cache`` is not configured.

    :param cache: The name of the requested cache.
    """
    try:
        # Check for proper Redis persistent backends
        # FIXME: this logic needs to be a system sanity check
        if (not settings.DEBUG and cache in PERSISTENT_STORES and
                (cache not in settings.CACHES or 'RedisCache' not in
                 settings.CACHES[cache]['BACKEND'] or
                 settings.CACHES[cache].get('TIMEOUT', '') is not None)):
            raise ImproperlyConfigured(
                'Pootle requires a Redis-backed caching backend for %r '
                'with `TIMEOUT: None`. Please review your settings.' % cache
            )

        return caches[cache]
    except InvalidCacheBackendError:
        return default_cache
项目:zing    作者:evernote    | 项目源码 | 文件源码
def check_config_for(cls, config_dict, username, require_email_fields=False):
        """Ensures the invoice configuration dictionary `config_dict` contains
        the required fields.

        :param username: Username owning the configuration.
        :param validate_email: Whether to also require email-related fields.
        """
        required_fields = (
            list(sum(cls.required_config_fields, ())) if require_email_fields else
            cls.required_config_fields[0]
        )
        missing_required_fields = [
            field for field in required_fields
            if field not in config_dict
        ]
        if len(missing_required_fields) > 0:
            raise ImproperlyConfigured(
                'The configuration for user %s is missing the following required '
                'fields: %s.\n'
                'Please double-check your configuration.'
                % (username, u', '.join(missing_required_fields))
            )

        return config_dict
项目:zing    作者:evernote    | 项目源码 | 文件源码
def import_func(path):
    i = path.rfind('.')
    module, attr = path[:i], path[i+1:]
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured('Error importing module %s: "%s"'
                                   % (module, e))
    try:
        func = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured(
            'Module "%s" does not define a "%s" callable function'
            % (module, attr))

    return func
项目:django-nameko    作者:and3rson    | 项目源码 | 文件源码
def get_pool():
    """
    Use this method to acquire connection pool.

    Example usage:

        from coreservices.core.rpc import get_pool
        # ...
        with get_pool().next() as rpc:
            rpc.mailer.send_mail(foo='bar')
    """
    create_pool_lock.acquire()
    global pool
    if not pool:
        # Lazy instantiation
        if not hasattr(settings, 'NAMEKO_CONFIG') or not settings.NAMEKO_CONFIG:
            raise ImproperlyConfigured('NAMEKO_CONFIG must be specified and should include at least "AMQP_URL" key.')
        pool = ClusterRpcProxyPool(settings.NAMEKO_CONFIG)
        pool.start()
    create_pool_lock.release()
    return pool
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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.")
        if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
                'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
            raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
                                       "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
def __init__(self, start, end, telescopes=None, sites=None, instrument_types=None):
        try:
            self.es = Elasticsearch([settings.ELASTICSEARCH_URL])
        except LocationValueError:
            logger.error('Could not find host. Make sure ELASTICSEARCH_URL is set.')
            raise ImproperlyConfigured('ELASTICSEARCH_URL')

        self.instrument_types = instrument_types
        self.available_telescopes = self._get_available_telescopes()

        sites = list({tk.site for tk in self.available_telescopes}) if not sites else sites
        telescopes = list({tk.telescope for tk in self.available_telescopes if tk.site in sites}) \
            if not telescopes else telescopes

        self.start = start.replace(tzinfo=timezone.utc).replace(microsecond=0)
        self.end = end.replace(tzinfo=timezone.utc).replace(microsecond=0)
        cached_event_data = cache.get('tel_event_data')
        if cached_event_data:
            self.event_data = cached_event_data
        else:
            self.event_data = self._get_es_data(sites, telescopes)
            cache.set('tel_event_data', self.event_data, 1800)
项目:django-openapi-gen    作者:Ecognize    | 项目源码 | 文件源码
def ready(self):
        self.schema = getattr(settings, 'SWAGGER_SCHEMA', None)

        if not self.schema:
            raise ImproperlyConfigured('You have to provide SWAGGER_SCHEMA setting pointing to desired schema')
        else:
            self.module = getattr(settings, 'SWAGGER_MODULE', None)
            self.swagger = Swagger(self.schema, self.module)
项目:django-openapi-gen    作者:Ecognize    | 项目源码 | 文件源码
def handle(self, *args, **options):
        schema = getattr(settings, 'SWAGGER_SCHEMA', None)
        module = getattr(settings, 'SWAGGER_MODULE', None)

        if not schema:
            raise ImproperlyConfigured('You have to provide SWAGGER_SCHEMA setting pointing to desired schema')
        if not module:
            raise ImproperlyConfigured('You have to specify desired controller module name in SWAGGER_MODULE setting')

        router = SwaggerRouter()

        print('Inspecting available controllers...')

        router.update(True)
        router.process()

        print()
        print('Following classes and methods are going to be generated:')

        enum = router.get_enum()

        for name in enum:
            print("{} : {}".format(name, [x['method'] for x in enum[name]['methods']]))

        if(options['generate']):
            template = Template()
            filename = module.split('.')[-1] + '.py'
            structure = [{ 'name' : name, 'data' : data } for name, data in six.iteritems(enum)]

            print('Generating handlers ({})...'.format(filename))

            with codecs.open(filename, 'w', 'utf-8') as f:
                f.write(template.render(template_name = 'view.jinja', names = structure))

            print('Done.')
        else:
            print()
            print('Use --generate option to create them')
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def test_build_version_missing_package_name(self, pkg):
        setattr(settings, 'HEARTBEAT', pkg)
        with pytest.raises(ImproperlyConfigured) as e:
            build.check(request=None)
        msg = 'Missing package_name key from heartbeat configuration'
        assert msg in str(e)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def test_prepare_redis(self):
        delattr(settings, 'CACHEOPS_REDIS')
        HEARTBEAT = {'checkers': ['heartbeat.checkers.redis_status']}
        with pytest.raises(ImproperlyConfigured) as e:
            heartbeat_settings.prepare_redis(HEARTBEAT)
        assert 'Missing CACHEOPS_REDIS in project settings' in str(e)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def test_missing_auth_configuration(self):
        self.heartbeat.pop('auth')
        with pytest.raises(ImproperlyConfigured) as e:
            request = self.factory.get(reverse('1337'))
            details(request)
        msg = 'Missing auth configuration for heartbeat'
        assert msg == str(e.value)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def test_missing_auth_credentials(self):
        self.heartbeat['auth'] = {'blow': 'fish'}
        with pytest.raises(ImproperlyConfigured) as e:
            request = self.factory.get(reverse('1337'))
            details(request)
        msg = ('Username or password missing from auth configuration '
               'for heartbeat')
        assert msg == str(e.value)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def check(request):
    package_name = settings.HEARTBEAT.get('package_name')
    if not package_name:
        raise ImproperlyConfigured(
            'Missing package_name key from heartbeat configuration')

    sys_path_distros = WorkingSet()
    package_req = Requirement.parse(package_name)

    distro = sys_path_distros.find(package_req)
    if not distro:
        return dict(error='no distribution found for {}'.format(package_name))

    return dict(name=distro.project_name, version=distro.version)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def prepare_credentials(auth):
    if not all([auth.get('username'), auth.get('password')]):
        raise ImproperlyConfigured(
            'Username or password missing from auth configuration '
            'for heartbeat')
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def prepare_redis(heartbeat):
    if 'heartbeat.checkers.redis_status' in heartbeat['checkers']:
        redis = getattr(settings, 'CACHEOPS_REDIS', None)
        if redis is None:
            raise ImproperlyConfigured(
                'Missing CACHEOPS_REDIS in project settings')
项目:cmsplugin-form-handler    作者:mkoistinen    | 项目源码 | 文件源码
def plugin(self):
        """
        Returns (instance, plugin) for the source plugin if found, else 404.
        """
        try:
            plugin_id = int(self.kwargs.get('plugin_id'))
            cms_plugin_instance = CMSPlugin.objects.get(pk=plugin_id)
        except (KeyError, TypeError, CMSPlugin.DoesNotExist):
            raise ImproperlyConfigured('Source form plugin not found.')
        return cms_plugin_instance.get_plugin_instance()