Exemplo n.º 1
0
    def _cursor(self):
        if self.connection is None:
            self._sqlite_create_connection()

            ## From here on, customized for GeoDjango ##

            # Enabling extension loading on the SQLite connection.
            try:
                self.connection.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 = self.connection.cursor(factory=SQLiteCursorWrapper)
            try:
                cur.execute("SELECT load_extension(%s)",
                            (self.spatialite_lib, ))
            except Exception, msg:
                raise ImproperlyConfigured(
                    'Unable to load the SpatiaLite library extension '
                    '"%s" because: %s' % (self.spatialite_lib, msg))
            return cur
def get_standard_processors():
    from my_django.conf import settings
    global _standard_context_processors
    if _standard_context_processors is None:
        processors = []
        collect = []
        collect.extend(_builtin_context_processors)
        collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS)
        for path in collect:
            i = path.rfind('.')
            module, attr = path[:i], path[i + 1:]
            try:
                mod = import_module(module)
            except ImportError, e:
                raise ImproperlyConfigured(
                    'Error importing request processor module %s: "%s"' %
                    (module, e))
            try:
                func = getattr(mod, attr)
            except AttributeError:
                raise ImproperlyConfigured(
                    'Module "%s" does not define a "%s" callable request processor'
                    % (module, attr))
            processors.append(func)
        _standard_context_processors = tuple(processors)
Exemplo n.º 3
0
 def __init__(self, apps=None, *args, **kwargs):
     # List of locations with static files
     self.locations = []
     # Maps dir paths to an appropriate storage instance
     self.storages = SortedDict()
     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 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)
    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 my_django.contrib.admin.models import LogEntry
        from my_django.contrib.contenttypes.models import ContentType

        if not LogEntry._meta.installed:
            raise ImproperlyConfigured(
                "Put 'django.contrib.admin' in your "
                "INSTALLED_APPS setting in order to use the admin application."
            )
        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 ('my_django.contrib.auth.context_processors.auth'
                in settings.TEMPLATE_CONTEXT_PROCESSORS
                or 'my_django.core.context_processors.auth'
                in settings.TEMPLATE_CONTEXT_PROCESSORS):
            raise ImproperlyConfigured(
                "Put 'my_django.contrib.auth.context_processors.auth' "
                "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application."
            )
def include(arg, namespace=None, app_name=None):
    if isinstance(arg, tuple):
        # callable returning a namespace hint
        if namespace:
            raise ImproperlyConfigured('Cannot override the namespace for a dynamic module that provides a namespace')
        urlconf_module, app_name, namespace = arg
    else:
        # No namespace hint - use manually provided namespace
        urlconf_module = arg

    if isinstance(urlconf_module, basestring):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)

    # Make sure we can iterate through the patterns (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            # Test if the LocaleRegexURLResolver is used within the include;
            # this should throw an error since this is not allowed!
            if isinstance(url_pattern, LocaleRegexURLResolver):
                raise ImproperlyConfigured(
                    'Using i18n_patterns in an included URLconf is not allowed.')

    return (urlconf_module, app_name, namespace)
def get_storage_class(import_path=None):
    if import_path is None:
        import_path = settings.DEFAULT_FILE_STORAGE
    try:
        dot = import_path.rindex('.')
    except ValueError:
        raise ImproperlyConfigured("%s isn't a storage module." % import_path)
    module, classname = import_path[:dot], import_path[dot + 1:]
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured('Error importing storage module %s: "%s"' %
                                   (module, e))
def get_storage(import_path):
    """
    Imports the message storage class described by import_path, where
    import_path is the full Python path to the class.
    """
    try:
        dot = import_path.rindex('.')
    except ValueError:
        raise ImproperlyConfigured("%s isn't a Python path." % import_path)
    module, classname = import_path[:dot], import_path[dot + 1:]
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured('Error importing module %s: "%s"' %
                                   (module, e))
 def __init__(self, request, params, model, model_admin):
     # This dictionary will eventually contain the request's query string
     # parameters actually used by this filter.
     self.used_parameters = {}
     if self.title is None:
         raise ImproperlyConfigured("The list filter '%s' does not specify "
                                    "a 'title'." % self.__class__.__name__)
Exemplo n.º 9
0
def get_internal_wsgi_application():
    """
    Loads and returns the WSGI application as configured by the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
    for Django's internal servers (runserver, runfcgi); external WSGI servers
    should just be configured to point to the correct application object
    directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), we just return
    whatever ``my_django.core.wsgi.get_wsgi_application`` returns.

    """
    from my_django.conf import settings
    app_path = getattr(settings, 'WSGI_APPLICATION')
    if app_path is None:
        return get_wsgi_application()
    module_name, attr = app_path.rsplit('.', 1)
    try:
        mod = import_module(module_name)
    except ImportError, e:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "could not import module '%s': %s" % (app_path, module_name, e))
Exemplo n.º 10
0
    def get_urls(self, page=1, site=None, protocol=None):
        # Determine protocol
        if self.protocol is not None:
            protocol = self.protocol
        if protocol is None:
            protocol = 'http'

        # Determine domain
        if site is None:
            if Site._meta.installed:
                try:
                    site = Site.objects.get_current()
                except Site.DoesNotExist:
                    pass
            if site is None:
                raise ImproperlyConfigured(
                    "To use sitemaps, either enable the sites framework or pass a Site/RequestSite object in your view."
                )
        domain = site.domain

        urls = []
        for item in self.paginator.page(page).object_list:
            loc = "%s://%s%s" % (protocol, domain, self.__get(
                'location', item))
            priority = self.__get('priority', item, None)
            url_info = {
                'item': item,
                'location': loc,
                'lastmod': self.__get('lastmod', item, None),
                'changefreq': self.__get('changefreq', item, None),
                'priority': str(priority is not None and priority or ''),
            }
            urls.append(url_info)
        return urls
Exemplo n.º 11
0
 def __init__(self, *args, **kwargs):
     super(DefaultStorageFinder, self).__init__(*args, **kwargs)
     base_location = getattr(self.storage, 'base_location', empty)
     if not base_location:
         raise ImproperlyConfigured("The storage backend of the "
                                    "staticfiles finder %r doesn't have "
                                    "a valid location." % self.__class__)
 def url_patterns(self):
     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
     try:
         iter(patterns)
     except TypeError:
         raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name)
     return patterns
Exemplo n.º 13
0
 def item_link(self, item):
     try:
         return item.get_absolute_url()
     except AttributeError:
         raise ImproperlyConfigured(
             'Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class.'
             % item.__class__.__name__)
Exemplo n.º 14
0
 def _sqlite_create_connection(self):
     settings_dict = self.settings_dict
     if not settings_dict['NAME']:
         from my_django.core.exceptions import ImproperlyConfigured
         raise ImproperlyConfigured(
             "Please fill out the database NAME in the settings module before using the database."
         )
     kwargs = {
         'database': settings_dict['NAME'],
         'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
     }
     kwargs.update(settings_dict['OPTIONS'])
     # Always allow the underlying SQLite connection to be shareable
     # between multiple threads. The safe-guarding will be handled at a
     # higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
     # property. This is necessary as the shareability is disabled by
     # default in pysqlite and it cannot be changed once a connection is
     # opened.
     if 'check_same_thread' in kwargs and kwargs['check_same_thread']:
         warnings.warn(
             'The `check_same_thread` option was provided and set to '
             'True. It will be overriden with False. Use the '
             '`DatabaseWrapper.allow_thread_sharing` property instead '
             'for controlling thread shareability.', RuntimeWarning)
     kwargs.update({'check_same_thread': False})
     self.connection = Database.connect(**kwargs)
     # Register extract, date_trunc, and regexp functions.
     self.connection.create_function("django_extract", 2, _sqlite_extract)
     self.connection.create_function("django_date_trunc", 2,
                                     _sqlite_date_trunc)
     self.connection.create_function("regexp", 2, _sqlite_regexp)
     self.connection.create_function("django_format_dtdelta", 5,
                                     _sqlite_format_dtdelta)
     connection_created.send(sender=self.__class__, connection=self)
 def process_request(self, request):
     # AuthenticationMiddleware is required so that request.user exists.
     if not hasattr(request, 'user'):
         raise ImproperlyConfigured(
             "The Django remote user auth middleware requires the"
             " authentication middleware to be installed.  Edit your"
             " MIDDLEWARE_CLASSES setting to insert"
             " 'my_django.contrib.auth.middleware.AuthenticationMiddleware'"
             " before the RemoteUserMiddleware class.")
     try:
         username = request.META[self.header]
     except KeyError:
         # If specified header doesn't exist then return (leaving
         # request.user set to AnonymousUser by the
         # AuthenticationMiddleware).
         return
     # If the user is already authenticated and that user is the user we are
     # getting passed in the headers, then the correct user is already
     # persisted in the session and we don't need to continue.
     if request.user.is_authenticated():
         if request.user.username == self.clean_username(username, request):
             return
     # We are seeing this user for the first time in this session, attempt
     # to authenticate the user.
     user = auth.authenticate(remote_user=username)
     if user:
         # User is valid.  Set request.user and persist user in the session
         # by logging the user in.
         request.user = user
         auth.login(request, user)
Exemplo n.º 16
0
    def load_spatialite_sql(self):
        """
        This routine loads up the SpatiaLite SQL file.
        """
        if self.connection.ops.spatial_version[:2] >= (3, 0):
            # Spatialite >= 3.0.x -- No need to load any SQL file, calling
            # InitSpatialMetaData() transparently creates the spatial metadata
            # tables
            cur = self.connection._cursor()
            cur.execute("SELECT InitSpatialMetaData()")
        else:
            # Spatialite < 3.0.x -- Load the initial SQL

            # Getting the location of the SpatiaLite SQL file, and confirming
            # it exists.
            spatialite_sql = self.spatialite_init_file()
            if not os.path.isfile(spatialite_sql):
                raise ImproperlyConfigured('Could not find the required SpatiaLite initialization '
                                        'SQL file (necessary for testing): %s' % spatialite_sql)

            # Opening up the SpatiaLite SQL initialization file and executing
            # as a script.
            sql_fh = open(spatialite_sql, 'r')
            try:
                cur = self.connection._cursor()
                cur.executescript(sql_fh.read())
            finally:
                sql_fh.close()
 def get_success_url(self):
     if self.success_url:
         url = self.success_url
     else:
         raise ImproperlyConfigured(
             "No URL to redirect to. Provide a success_url.")
     return url
def serve(request, path, document_root=None, insecure=False, **kwargs):
    """
    Serve static files below a given point in the directory structure or
    from locations inferred from the staticfiles finders.

    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve')

    in your URLconf.

    It uses the django.views.static view to serve the found files.
    """
    if not settings.DEBUG and not insecure:
        raise ImproperlyConfigured("The staticfiles view can only be used in "
                                   "debug mode or if the the --insecure "
                                   "option of 'runserver' is used")
    normalized_path = posixpath.normpath(urllib.unquote(path)).lstrip('/')
    absolute_path = finders.find(normalized_path)
    if not absolute_path:
        if path.endswith('/') or path == '':
            raise Http404("Directory indexes are not allowed here.")
        raise Http404("'%s' could not be found" % path)
    document_root, path = os.path.split(absolute_path)
    return static.serve(request, path, document_root=document_root, **kwargs)
Exemplo n.º 19
0
def get_cookie_signer(salt='my_django.core.signing.get_cookie_signer'):
    modpath = settings.SIGNING_BACKEND
    module, attr = modpath.rsplit('.', 1)
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured('Error importing cookie signer %s: "%s"' %
                                   (modpath, e))
def load_backend(path):
    i = path.rfind('.')
    module, attr = path[:i], path[i + 1:]
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured(
            'Error importing authentication backend %s: "%s"' % (path, e))
Exemplo n.º 21
0
 def get_date_field(self):
     """
     Get the name of the date field to be used to filter by.
     """
     if self.date_field is None:
         raise ImproperlyConfigured(u"%s.date_field is required." %
                                    self.__class__.__name__)
     return self.date_field
Exemplo n.º 22
0
def get_exception_reporter_filter(request):
    global default_exception_reporter_filter
    if default_exception_reporter_filter is None:
        # Load the default filter for the first time and cache it.
        modpath = settings.DEFAULT_EXCEPTION_REPORTER_FILTER
        modname, classname = modpath.rsplit('.', 1)
        try:
            mod = import_module(modname)
        except ImportError, e:
            raise ImproperlyConfigured(
                'Error importing default exception reporter filter %s: "%s"' %
                (modpath, e))
        try:
            default_exception_reporter_filter = getattr(mod, classname)()
        except AttributeError:
            raise ImproperlyConfigured(
                'Default exception reporter filter module "%s" does not define a "%s" class'
                % (modname, classname))
Exemplo n.º 23
0
    def __init__(self, connection):
        super(DatabaseOperations, self).__init__(connection)

        # Determine the version of the SpatiaLite library.
        try:
            vtup = self.spatialite_version_tuple()
            version = vtup[1:]
            if version < (2, 3, 0):
                raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions '
                                           '2.3.0 and above')
            self.spatial_version = version
        except ImproperlyConfigured:
            raise
        except Exception, msg:
            raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" '
                                       'database (error was "%s").  Was the SpatiaLite initialization '
                                       'SQL loaded on this database?' %
                                       (self.connection.settings_dict['NAME'], msg))
Exemplo n.º 24
0
def get_comment_app():
    """
    Get the comment app (i.e. "django.contrib.comments") as defined in the settings
    """
    # Make sure the app's in INSTALLED_APPS
    comments_app = get_comment_app_name()
    if comments_app not in settings.INSTALLED_APPS:
        raise ImproperlyConfigured("The COMMENTS_APP (%r) "\
                                   "must be in INSTALLED_APPS" % settings.COMMENTS_APP)

    # Try to import the package
    try:
        package = import_module(comments_app)
    except ImportError:
        raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\
                                   "a non-existing package.")

    return package
def find_template_loader(loader):
    if isinstance(loader, (tuple, list)):
        loader, args = loader[0], loader[1:]
    else:
        args = []
    if isinstance(loader, basestring):
        module, attr = loader.rsplit('.', 1)
        try:
            mod = import_module(module)
        except ImportError, e:
            raise ImproperlyConfigured(
                'Error importing template source loader %s: "%s"' %
                (loader, e))
        try:
            TemplateLoader = getattr(mod, attr)
        except AttributeError, e:
            raise ImproperlyConfigured(
                'Error importing template source loader %s: "%s"' %
                (loader, e))
def get_backends():
    from my_django.conf import settings
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backends.append(load_backend(backend_path))
    if not backends:
        raise ImproperlyConfigured(
            'No authentication backends have been defined. Does AUTHENTICATION_BACKENDS contain anything?'
        )
    return backends
Exemplo n.º 27
0
def _get_finder(import_path):
    """
    Imports the staticfiles finder class described by import_path, where
    import_path is the full Python path to the class.
    """
    module, attr = import_path.rsplit('.', 1)
    try:
        mod = import_module(module)
    except ImportError, e:
        raise ImproperlyConfigured('Error importing module %s: "%s"' %
                                   (module, e))
 def get_success_url(self):
     if self.success_url:
         url = self.success_url % 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
def load_hashers(password_hashers=None):
    global HASHERS
    global PREFERRED_HASHER
    hashers = []
    if not password_hashers:
        password_hashers = settings.PASSWORD_HASHERS
    for backend in password_hashers:
        try:
            mod_path, cls_name = backend.rsplit('.', 1)
            mod = importlib.import_module(mod_path)
            hasher_cls = getattr(mod, cls_name)
        except (AttributeError, ImportError, ValueError):
            raise ImproperlyConfigured("hasher not found: %s" % backend)
        hasher = hasher_cls()
        if not getattr(hasher, 'algorithm'):
            raise ImproperlyConfigured("hasher doesn't specify an "
                                       "algorithm name: %s" % backend)
        hashers.append(hasher)
    HASHERS = dict([(hasher.algorithm, hasher) for hasher in hashers])
    PREFERRED_HASHER = hashers[0]
 def get_template_names(self):
     """
     Returns 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.
     """
     if self.template_name is None:
         raise ImproperlyConfigured(
             "TemplateResponseMixin requires either a definition of "
             "'template_name' or an implementation of 'get_template_names()'")
     else:
         return [self.template_name]