Python django.core.exceptions.ImproperlyConfigured() Examples

The following are code examples for showing how to use django.core.exceptions.ImproperlyConfigured(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: CodingDojo   Author: ComputerSocietyUNB   File: finders.py    (license) View Source Project 7 votes vote down vote up
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) 
Example 2
Project: NearBeach   Author: robotichead   File: private_media.py    (MIT License) View Source Project 6 votes vote down vote up
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)) 
Example 3
Project: cmsplugin-form-handler   Author: mkoistinen   File: test_plugins.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 4
Project: cmsplugin-form-handler   Author: mkoistinen   File: test_plugins.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 5
Project: oscars2016   Author: 0x0ece   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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") 
Example 6
Project: oscars2016   Author: 0x0ece   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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'.") 
Example 7
Project: minimum-entropy   Author: DistrictDataLabs   File: base.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 8
Project: django-ajax-views   Author: Pyco7   File: queries.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 9
Project: CodingDojo   Author: ComputerSocietyUNB   File: urlresolvers.py    (license) View Source Project 6 votes vote down vote up
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] 
Example 10
Project: CodingDojo   Author: ComputerSocietyUNB   File: file.py    (license) View Source Project 6 votes vote down vote up
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 
Example 11
Project: CodingDojo   Author: ComputerSocietyUNB   File: models.py    (license) View Source Project 6 votes vote down vote up
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."
        ) 
Example 12
Project: CodingDojo   Author: ComputerSocietyUNB   File: utils.py    (license) View Source Project 6 votes vote down vote up
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") 
Example 13
Project: CodingDojo   Author: ComputerSocietyUNB   File: base.py    (license) View Source Project 6 votes vote down vote up
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 
Example 14
Project: CodingDojo   Author: ComputerSocietyUNB   File: base.py    (license) View Source Project 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'] == '':
            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 15
Project: CodingDojo   Author: ComputerSocietyUNB   File: base.py    (license) View Source Project 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 16
Project: CodingDojo   Author: ComputerSocietyUNB   File: operations.py    (license) View Source Project 6 votes vote down vote up
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] 
Example 17
Project: CodingDojo   Author: ComputerSocietyUNB   File: engine.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 18
Project: CodingDojo   Author: ComputerSocietyUNB   File: edit.py    (license) View Source Project 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 19
Project: CodingDojo   Author: ComputerSocietyUNB   File: list.py    (license) View Source Project 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 20
Project: CodingDojo   Author: ComputerSocietyUNB   File: detail.py    (license) View Source Project 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 21
Project: CodingDojo   Author: ComputerSocietyUNB   File: static.py    (license) View Source Project 6 votes vote down vote up
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),
    ] 
Example 22
Project: CodingDojo   Author: ComputerSocietyUNB   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 23
Project: CodingDojo   Author: ComputerSocietyUNB   File: __init__.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 24
Project: NarshaTech   Author: KimJangHyeon   File: file.py    (license) View Source Project 6 votes vote down vote up
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 
Example 25
Project: NarshaTech   Author: KimJangHyeon   File: models.py    (license) View Source Project 6 votes vote down vote up
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."
        ) 
Example 26
Project: NarshaTech   Author: KimJangHyeon   File: finders.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 27
Project: NarshaTech   Author: KimJangHyeon   File: base.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 28
Project: NarshaTech   Author: KimJangHyeon   File: base.py    (license) View Source Project 6 votes vote down vote up
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 
Example 29
Project: NarshaTech   Author: KimJangHyeon   File: options.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 30
Project: django-modeltrans   Author: zostera   File: test_translating.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 31
Project: django-modeltrans   Author: zostera   File: conf.py    (license) View Source Project 6 votes vote down vote up
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()) 
Example 32
Project: django-tree   Author: BertrandBordage   File: operations.py    (license) View Source Project 6 votes vote down vote up
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 
Example 33
Project: zing   Author: evernote   File: cache.py    (license) View Source Project 6 votes vote down vote up
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 
Example 34
Project: zing   Author: evernote   File: invoice.py    (license) View Source Project 6 votes vote down vote up
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 
Example 35
Project: zing   Author: evernote   File: util.py    (license) View Source Project 6 votes vote down vote up
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 
Example 36
Project: django-nameko   Author: and3rson   File: rpc.py    (license) View Source Project 6 votes vote down vote up
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 
Example 37
Project: blog_django   Author: chnpmy   File: sites.py    (license) View Source Project 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.")
        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.") 
Example 38
Project: valhalla   Author: LCOGT   File: telescope_states.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 39
Project: django-openapi-gen   Author: Ecognize   File: apps.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 40
Project: django-openapi-gen   Author: Ecognize   File: swaggertool.py    (MIT License) View Source Project 5 votes vote down vote up
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') 
Example 41
Project: django-heartbeat   Author: pbs   File: test_checkers.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 42
Project: django-heartbeat   Author: pbs   File: test_checkers.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 43
Project: django-heartbeat   Author: pbs   File: test_views.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 44
Project: django-heartbeat   Author: pbs   File: test_views.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 45
Project: django-heartbeat   Author: pbs   File: build.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 46
Project: django-heartbeat   Author: pbs   File: auth.py    (MIT License) View Source Project 5 votes vote down vote up
def prepare_credentials(auth):
    if not all([auth.get('username'), auth.get('password')]):
        raise ImproperlyConfigured(
            'Username or password missing from auth configuration '
            'for heartbeat') 
Example 47
Project: django-heartbeat   Author: pbs   File: settings.py    (MIT License) View Source Project 5 votes vote down vote up
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') 
Example 48
Project: cmsplugin-form-handler   Author: mkoistinen   File: views.py    (MIT License) View Source Project 5 votes vote down vote up
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() 
Example 49
Project: cmsplugin-form-handler   Author: mkoistinen   File: views.py    (MIT License) View Source Project 5 votes vote down vote up
def get_form_class(self):
        instance, plugin = self.plugin
        try:
            return plugin.get_form_class(self.request, instance)
        except (AttributeError, TypeError):
            raise ImproperlyConfigured(
                'Source form plugin does not define `get_form_class()`.') 
Example 50
Project: cmsplugin-form-handler   Author: mkoistinen   File: views.py    (MIT License) View Source Project 5 votes vote down vote up
def get_success_url(self):
        instance, plugin = self.plugin
        try:
            url = plugin.get_success_url(self.request, instance)
            return url
        except AttributeError:
            raise ImproperlyConfigured(
                'Source plugin does not define `get_success_url()`.')