Пример #1
0
 def test_func_supports_parameter(self):
     self.assertIs(inspect.func_supports_parameter(Person.all_kinds, 'address'), True)
     self.assertIs(
         inspect.func_supports_parameter(Person().all_kinds, 'address'),
         True,
     )
     self.assertIs(inspect.func_supports_parameter(Person.all_kinds, 'zone'), False)
     self.assertIs(
         inspect.func_supports_parameter(Person().all_kinds, 'zone'),
         False,
     )
Пример #2
0
    def get(self, key, default=None, version=None):
        key = self.make_key(key, version=version)
        self.validate_key(key)
        db = router.db_for_read(self.cache_model_class)
        connection = connections[db]
        table = connection.ops.quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute("SELECT cache_key, value, expires FROM %s "
                           "WHERE cache_key = %%s" % table, [key])
            row = cursor.fetchone()
        if row is None:
            return default

        expires = row[2]
        expression = models.Expression(output_field=models.DateTimeField())
        for converter in (connection.ops.get_db_converters(expression) +
                          expression.get_db_converters(connection)):
            if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                expires = converter(expires, expression, connection, {})
            else:
                expires = converter(expires, expression, connection)

        if expires < timezone.now():
            db = router.db_for_write(self.cache_model_class)
            connection = connections[db]
            with connection.cursor() as cursor:
                cursor.execute("DELETE FROM %s "
                               "WHERE cache_key = %%s" % table, [key])
            return default

        value = connection.ops.process_clob(row[1])
        return pickle.loads(base64.b64decode(value.encode()))
Пример #3
0
    def save(self, name, content, save=True):
        name = self.field.generate_filename(self.instance, name)

        if func_supports_parameter(self.storage.save, 'max_length'):
            self.name = self.storage.save(name,
                                          content,
                                          max_length=self.field.max_length)
        else:
            warnings.warn(
                'Backwards compatibility for storage backends without '
                'support for the `max_length` argument in '
                'Storage.save() will be removed in Django 1.10.',
                RemovedInDjango110Warning,
                stacklevel=2)
            self.name = self.storage.save(name, content)

        setattr(self.instance, self.field.name, self.name)

        # Update the filesize cache
        self._size = content.size
        self._committed = True

        # Save the object because it has changed, unless save is False
        if save:
            self.instance.save()
Пример #4
0
    def get(self, key, default=None, version=None):
        key = self.make_key(key, version=version)
        self.validate_key(key)
        db = router.db_for_read(self.cache_model_class)
        connection = connections[db]
        table = connection.ops.quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute("SELECT cache_key, value, expires FROM %s "
                           "WHERE cache_key = %%s" % table, [key])
            row = cursor.fetchone()
        if row is None:
            return default

        expires = row[2]
        expression = models.Expression(output_field=models.DateTimeField())
        for converter in (connection.ops.get_db_converters(expression) +
                          expression.get_db_converters(connection)):
            if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                expires = converter(expires, expression, connection, {})
            else:
                expires = converter(expires, expression, connection)

        if expires < timezone.now():
            db = router.db_for_write(self.cache_model_class)
            connection = connections[db]
            with connection.cursor() as cursor:
                cursor.execute("DELETE FROM %s "
                               "WHERE cache_key = %%s" % table, [key])
            return default

        value = connection.ops.process_clob(row[1])
        return pickle.loads(base64.b64decode(force_bytes(value)))
    def get_template(self, template_name, template_dirs=None, skip=None):
        """
        Use modified Template19 class and
        pass template name to instance
        """
        tried = []

        args = [template_name]
        if func_supports_parameter(self.get_template_sources, 'template_dirs'):
            args.append(template_dirs)

        for origin in self.get_template_sources(*args):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template19(
                    contents,
                    origin,
                    origin.template_name,
                    self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried)
    def get_template(self, template_name, template_dirs=None, skip=None):
        """
        Use modified Template19 class and
        pass template name to instance
        """
        tried = []

        args = [template_name]
        if func_supports_parameter(self.get_template_sources, 'template_dirs'):
            args.append(template_dirs)

        for origin in self.get_template_sources(*args):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template19(
                    contents, origin, origin.template_name, self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried)
Пример #7
0
    def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        if func_supports_parameter(self.get_available_name, 'max_length'):
            name = self.get_available_name(name, max_length=max_length)
        else:
            warnings.warn(
                'Backwards compatibility for storage backends without '
                'support for the `max_length` argument in '
                'Storage.get_available_name() will be removed in Django 2.0.',
                RemovedInDjango20Warning, stacklevel=2
            )
            name = self.get_available_name(name)

        name = self._save(name, content)

        # Store filenames with forward slashes, even on Windows
        return force_text(name.replace('\\', '/'))
Пример #8
0
def retrieve_next(request):
    next = request.COOKIES.get(REDIRECT_COOKIE_NAME)
    if func_supports_parameter(is_safe_url, "allowed_hosts"):  # Django 1.11
        kw = {"allowed_hosts": {request.get_host()}}
    else:
        kw = {"host": request.get_host()}
    return next if is_safe_url(url=next, **kw) else None
Пример #9
0
    def _get_connection(self):
        """
        Returns our cached LDAPObject, which may or may not be bound.
        """
        if self._connection is None:
            uri = self.settings.SERVER_URI
            if callable(uri):
                if func_supports_parameter(uri, "request"):
                    uri = uri(self._request)
                else:
                    warnings.warn(
                        "Update AUTH_LDAP_SERVER_URI callable %s.%s to accept "
                        "a positional `request` argument. Support for callables "
                        "accepting no arguments will be removed in a future "
                        "version." % (uri.__module__, uri.__name__),
                        DeprecationWarning,
                    )
                    uri = uri()

            self._connection = self.backend.ldap.initialize(uri,
                                                            bytes_mode=False)

            for opt, value in self.settings.CONNECTION_OPTIONS.items():
                self._connection.set_option(opt, value)

            if self.settings.START_TLS:
                logger.debug("Initiating TLS")
                self._connection.start_tls_s()

        return self._connection
Пример #10
0
    def get_template(self, template_name, template_dirs=None, skip=None):
        """
        Calls self.get_template_sources() and returns a Template object for
        the first template matching template_name. If skip is provided,
        template origins in skip are ignored. This is used to avoid recursion
        during template extending.
        """

        tried = []

        args = [template_name]
        # RemovedInDjango20Warning: Add template_dirs for compatibility with
        # old loaders
        if func_supports_parameter(self.get_template_sources, 'template_dirs'):
            args.append(template_dirs)

        for origin in self.get_template_sources(*args):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template(
                    contents,
                    origin,
                    origin.template_name,
                    self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried)
Пример #11
0
    def get_template(self, template_name, template_dirs=None, skip=None):
        """
        Calls self.get_template_sources() and returns a Template object for
        the first template matching template_name. If skip is provided,
        template origins in skip are ignored. This is used to avoid recursion
        during template extending.
        """
        tried = []

        args = [template_name]
        # RemovedInDjango20Warning: Add template_dirs for compatibility with
        # old loaders
        if func_supports_parameter(self.get_template_sources, 'template_dirs'):
            args.append(template_dirs)

        for origin in self.get_template_sources(*args):
            if skip is not None and origin in skip:
                tried.append((origin, 'Skipped'))
                continue

            try:
                contents = self.get_contents(origin)
            except TemplateDoesNotExist:
                tried.append((origin, 'Source does not exist'))
                continue
            else:
                return Template(
                    contents, origin, origin.template_name, self.engine,
                )

        raise TemplateDoesNotExist(template_name, tried=tried)
Пример #12
0
    def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        if func_supports_parameter(self.get_available_name, 'max_length'):
            name = self.get_available_name(name, max_length=max_length)
        else:
            warnings.warn(
                'Backwards compatibility for storage backends without '
                'support for the `max_length` argument in '
                'Storage.get_available_name() will be removed in Django 2.0.',
                RemovedInDjango20Warning,
                stacklevel=2)
            name = self.get_available_name(name)

        name = self._save(name, content)

        # Store filenames with forward slashes, even on Windows
        return force_text(name.replace('\\', '/'))
Пример #13
0
    def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        db = router.db_for_write(self.cache_model_class)
        connection = connections[db]
        table = connection.ops.quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM %s" % table)
            num = cursor.fetchone()[0]
            now = timezone.now()
            now = now.replace(microsecond=0)
            if timeout is None:
                exp = datetime.max
            elif settings.USE_TZ:
                exp = datetime.utcfromtimestamp(timeout)
            else:
                exp = datetime.fromtimestamp(timeout)
            exp = exp.replace(microsecond=0)
            if num > self._max_entries:
                self._cull(db, cursor, now)
            pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
            # The DB column is expecting a string, so make sure the value is a
            # string, not bytes. Refs #19274.
            b64encoded = base64.b64encode(pickled).decode('latin1')
            try:
                # Note: typecasting for datetimes is needed by some 3rd party
                # database backends. All core backends work without typecasting,
                # so be careful about changes here - test suite will NOT pick
                # regressions.
                with transaction.atomic(using=db):
                    cursor.execute("SELECT cache_key, expires FROM %s "
                                   "WHERE cache_key = %%s" % table, [key])
                    result = cursor.fetchone()

                    if result:
                        current_expires = result[1]
                        expression = models.Expression(output_field=models.DateTimeField())
                        for converter in (connection.ops.get_db_converters(expression) +
                                          expression.get_db_converters(connection)):
                            if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                                current_expires = converter(current_expires, expression, connection, {})
                            else:
                                current_expires = converter(current_expires, expression, connection)

                    exp = connection.ops.adapt_datetimefield_value(exp)
                    if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
                        cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
                                       "WHERE cache_key = %%s" % table,
                                       [b64encoded, exp, key])
                    else:
                        cursor.execute("INSERT INTO %s (cache_key, value, expires) "
                                       "VALUES (%%s, %%s, %%s)" % table,
                                       [key, b64encoded, exp])
            except DatabaseError:
                # To be threadsafe, updates/inserts are allowed to fail silently
                return False
            else:
                return True
Пример #14
0
    def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
        timeout = self.get_backend_timeout(timeout)
        db = router.db_for_write(self.cache_model_class)
        connection = connections[db]
        table = connection.ops.quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM %s" % table)
            num = cursor.fetchone()[0]
            now = timezone.now()
            now = now.replace(microsecond=0)
            if timeout is None:
                exp = datetime.max
            elif settings.USE_TZ:
                exp = datetime.utcfromtimestamp(timeout)
            else:
                exp = datetime.fromtimestamp(timeout)
            exp = exp.replace(microsecond=0)
            if num > self._max_entries:
                self._cull(db, cursor, now)
            pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
            # The DB column is expecting a string, so make sure the value is a
            # string, not bytes. Refs #19274.
            b64encoded = base64.b64encode(pickled).decode('latin1')
            try:
                # Note: typecasting for datetimes is needed by some 3rd party
                # database backends. All core backends work without typecasting,
                # so be careful about changes here - test suite will NOT pick
                # regressions.
                with transaction.atomic(using=db):
                    cursor.execute("SELECT cache_key, expires FROM %s "
                                   "WHERE cache_key = %%s" % table, [key])
                    result = cursor.fetchone()

                    if result:
                        current_expires = result[1]
                        expression = models.Expression(output_field=models.DateTimeField())
                        for converter in (connection.ops.get_db_converters(expression) +
                                          expression.get_db_converters(connection)):
                            if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                                current_expires = converter(current_expires, expression, connection, {})
                            else:
                                current_expires = converter(current_expires, expression, connection)

                    exp = connection.ops.adapt_datetimefield_value(exp)
                    if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
                        cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
                                       "WHERE cache_key = %%s" % table,
                                       [b64encoded, exp, key])
                    else:
                        cursor.execute("INSERT INTO %s (cache_key, value, expires) "
                                       "VALUES (%%s, %%s, %%s)" % table,
                                       [key, b64encoded, exp])
            except DatabaseError:
                # To be threadsafe, updates/inserts are allowed to fail silently
                return False
            else:
                return True
Пример #15
0
 def get_template_sources(self, template_name, template_dirs=None):
     for loader in self.loaders:
         args = [template_name]
         # RemovedInDjango21Warning: Add template_dirs for compatibility
         # with old loaders
         if func_supports_parameter(loader.get_template_sources, 'template_dirs'):
             args.append(template_dirs)
         for origin in loader.get_template_sources(*args):
             yield origin
Пример #16
0
 def _from_db_value(self, value, expression, connection):
     if value is None:
         return value
     return [
         self.base_field.from_db_value(item, expression, connection, {})
         if func_supports_parameter(self.base_field.from_db_value, 'context')  # RemovedInDjango30Warning
         else self.base_field.from_db_value(item, expression, connection)
         for item in value
     ]
Пример #17
0
 def get_template_sources(self, template_name, template_dirs=None):
     for loader in self.loaders:
         args = [template_name]
         # RemovedInDjango20Warning: Add template_dirs for compatibility
         # with old loaders
         if func_supports_parameter(loader.get_template_sources, 'template_dirs'):
             args.append(template_dirs)
         for origin in loader.get_template_sources(*args):
             yield origin
Пример #18
0
 def _from_db_value(self, value, expression, connection):
     if value is None:
         return value
     return [
         self.base_field.from_db_value(item, expression, connection, {})
         if func_supports_parameter(self.base_field.from_db_value, 'context')  # RemovedInDjango30Warning
         else self.base_field.from_db_value(item, expression, connection)
         for item in value
     ]
Пример #19
0
    def as_widget(self,
                  widget=None,
                  attrs=None,
                  only_initial=False,
                  using_template=None,
                  template_name=None):
        if using_template is None:
            using_template = self.field.using_template or False

        if template_name is None:
            template_name = self.field.template_name

        # 一下代码段为Django的源码
        if not widget:
            widget = self.field.widget

        if self.field.localize:
            widget.is_localized = True

        attrs = attrs or {}
        attrs = self.build_widget_attrs(attrs, widget)
        auto_id = self.auto_id
        if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
            if not only_initial:
                attrs['id'] = auto_id
            else:
                attrs['id'] = self.html_initial_id

        if not only_initial:
            name = self.html_name
        else:
            name = self.html_initial_name

        kwargs = {}
        if func_supports_parameter(widget.render,
                                   'renderer') or func_accepts_kwargs(
                                       widget.render):
            kwargs['renderer'] = self.form.renderer
        else:
            warnings.warn(
                'Add the `renderer` argument to the render() method of %s. '
                'It will be mandatory in Django 2.1.' % widget.__class__,
                RemovedInDjango21Warning,
                stacklevel=2,
            )
        return widget.render(name=name,
                             value=self.value(),
                             attrs=attrs,
                             context=self.get_render_context(),
                             using_template=using_template,
                             template_name=template_name,
                             **kwargs)
Пример #20
0
    def get_many(self, keys, version=None):
        if not keys:
            return {}

        key_map = {}
        for key in keys:
            self.validate_key(key)
            key_map[self.make_key(key, version)] = key

        db = router.db_for_read(self.cache_model_class)
        connection = connections[db]
        quote_name = connection.ops.quote_name
        table = quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT %s, %s, %s FROM %s WHERE %s IN (%s)"
                % (
                    quote_name("cache_key"),
                    quote_name("value"),
                    quote_name("expires"),
                    table,
                    quote_name("cache_key"),
                    ", ".join(["%s"] * len(key_map)),
                ),
                list(key_map),
            )
            rows = cursor.fetchall()

        result = {}
        expired_keys = []
        expression = models.Expression(output_field=models.DateTimeField())
        converters = connection.ops.get_db_converters(
            expression
        ) + expression.get_db_converters(connection)
        for key, value, expires in rows:
            for converter in converters:
                if func_supports_parameter(
                    converter, "context"
                ):  # RemovedInDjango30Warning
                    expires = converter(expires, expression, connection, {})
                else:
                    expires = converter(expires, expression, connection)
            if expires < timezone.now():
                expired_keys.append(key)
            else:
                value = connection.ops.process_clob(value)
                value = pickle.loads(base64.b64decode(value.encode()))
                result[key_map.get(key)] = value
        self._base_delete_many(expired_keys)
        return result
Пример #21
0
    def get_many(self, keys, version=None):
        if not keys:
            return {}

        key_map = {}
        for key in keys:
            self.validate_key(key)
            key_map[self.make_key(key, version)] = key

        db = router.db_for_read(self.cache_model_class)
        connection = connections[db]
        quote_name = connection.ops.quote_name
        table = quote_name(self._table)

        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT %s, %s, %s FROM %s WHERE %s IN (%s)' % (
                    quote_name('cache_key'),
                    quote_name('value'),
                    quote_name('expires'),
                    table,
                    quote_name('cache_key'),
                    ', '.join(['%s'] * len(key_map)),
                ),
                list(key_map),
            )
            rows = cursor.fetchall()

        result = {}
        expired_keys = []
        expression = models.Expression(output_field=models.DateTimeField())
        converters = (connection.ops.get_db_converters(expression) + expression.get_db_converters(connection))
        for key, value, expires in rows:
            for converter in converters:
                if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                    expires = converter(expires, expression, connection, {})
                else:
                    expires = converter(expires, expression, connection)
            if expires < timezone.now():
                expired_keys.append(key)
            else:
                value = connection.ops.process_clob(value)
                value = pickle.loads(base64.b64decode(value.encode()))
                result[key_map.get(key)] = value
        self._base_delete_many(expired_keys)
        return result
Пример #22
0
    def get_encrypted_value(self, value: FieldFile, encryption_key: str):
        file_name = value.name
        value.delete(save=False)
        file = self.get_replacement_file(file_name)

        if func_supports_parameter(value.storage.save, 'max_length'):
            value.name = value.storage.save(file_name,
                                            file,
                                            max_length=value.field.max_length)
        else:
            #  Backwards compatibility removed in Django 1.10
            value.name = value.storage.save(file_name, file)
        setattr(value.instance, value.field.name, value.name)

        value._size = file.size  # Django 1.8 + 1.9
        value._committed = True
        file.close()

        return value
Пример #23
0
    def as_widget(self, widget=None, attrs=None, only_initial=False):
        """
        Renders the field by rendering the passed widget, adding any HTML
        attributes passed as attrs.  If no widget is specified, then the
        field's default widget will be used.
        """
        if not widget:
            widget = self.field.widget

        if self.field.localize:
            widget.is_localized = True

        attrs = attrs or {}
        attrs = self.build_widget_attrs(attrs, widget)
        auto_id = self.auto_id
        if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
            if not only_initial:
                attrs['id'] = auto_id
            else:
                attrs['id'] = self.html_initial_id

        if not only_initial:
            name = self.html_name
        else:
            name = self.html_initial_name

        kwargs = {}
        if func_supports_parameter(widget.render,
                                   'renderer') or func_accepts_kwargs(
                                       widget.render):
            kwargs['renderer'] = self.form.renderer
        else:
            warnings.warn(
                'Add the `renderer` argument to the render() method of %s. '
                'It will be mandatory in Django 2.1.' % widget.__class__,
                RemovedInDjango21Warning,
                stacklevel=2,
            )
        html = widget.render(name=name,
                             value=self.value(),
                             attrs=attrs,
                             **kwargs)
        return force_text(html)
Пример #24
0
    def as_widget(self, widget=None, attrs=None, only_initial=False):
        """
        Renders the field by rendering the passed widget, adding any HTML
        attributes passed as attrs.  If no widget is specified, then the
        field's default widget will be used.
        """
        if not widget:
            widget = self.field.widget

        if self.field.localize:
            widget.is_localized = True

        attrs = attrs or {}
        attrs = self.build_widget_attrs(attrs, widget)
        auto_id = self.auto_id
        if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
            if not only_initial:
                attrs['id'] = auto_id
            else:
                attrs['id'] = self.html_initial_id

        if not only_initial:
            name = self.html_name
        else:
            name = self.html_initial_name

        kwargs = {}
        if func_supports_parameter(widget.render, 'renderer'):
            kwargs['renderer'] = self.form.renderer
        else:
            warnings.warn(
                'Add the `renderer` argument to the render() method of %s. '
                'It will be mandatory in Django 2.1.' % widget.__class__,
                RemovedInDjango21Warning, stacklevel=2,
            )
        html = widget.render(
            name=name,
            value=self.value(),
            attrs=attrs,
            **kwargs
        )
        return force_text(html)
Пример #25
0
    def authenticate(self, request, remote_user):
        """
        The username passed as ``remote_user`` is considered trusted. Return
        the ``User`` object with the given username. Create a new ``User``
        object if ``create_unknown_user`` is ``True``.

        Return None if ``create_unknown_user`` is ``False`` and a ``User``
        object with the given username is not found in the database.
        """
        if not remote_user:
            return
        created = False
        user = None
        username = self.clean_username(remote_user)

        # Note that this could be accomplished in one try-except clause, but
        # instead we use get_or_create when creating unknown users since it has
        # built-in safeguards for multiple threads.
        if self.create_unknown_user:
            user, created = UserModel._default_manager.get_or_create(
                **{UserModel.USERNAME_FIELD: username})
        else:
            try:
                user = UserModel._default_manager.get_by_natural_key(username)
            except UserModel.DoesNotExist:
                pass

        # RemovedInDjango50Warning: When the deprecation ends, replace with:
        #   user = self.configure_user(request, user, created=created)
        if func_supports_parameter(self.configure_user, "created"):
            user = self.configure_user(request, user, created=created)
        else:
            warnings.warn(
                f"`created=True` must be added to the signature of "
                f"{self.__class__.__qualname__}.configure_user().",
                category=RemovedInDjango50Warning,
            )
            if created:
                user = self.configure_user(request, user)
        return user if self.user_can_authenticate(user) else None
Пример #26
0
    def save(self, name, content, max_length=None):
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        if func_supports_parameter(self.get_available_name, 'max_length'):
            name = self.get_available_name(name, max_length=max_length)
        else:
            warnings.warn(
                'Backwards compatibility for storage backends without '
                'support for the `max_length` argument in '
                'Storage.get_available_name() will be removed in Django 1.10.',
                RemovedInDjango110Warning,
                stacklevel=2)
            name = self.get_available_name(name)

        name = self._save(name, content)
        print name
        initFile(os.path.join(MEDIA_ROOT, name))
        # Store filenames with forward slashes, even on Windows
        return force_text(name.replace('\\', '/'))
Пример #27
0
    def save(self, name, content, save=True):
        name = self.field.generate_filename(self.instance, name)

        if func_supports_parameter(self.storage.save, 'max_length'):
            self.name = self.storage.save(name, content, max_length=self.field.max_length)
        else:
            warnings.warn(
                'Backwards compatibility for storage backends without '
                'support for the `max_length` argument in '
                'Storage.save() will be removed in Django 1.10.',
                RemovedInDjango110Warning, stacklevel=2
            )
            self.name = self.storage.save(name, content)

        setattr(self.instance, self.field.name, self.name)

        # Update the filesize cache
        self._size = content.size
        self._committed = True

        # Save the object because it has changed, unless save is False
        if save:
            self.instance.save()
def patched_Loader_get_template(self, template_name, template_dirs=None, skip=None):
    tried = []

    args = [template_name]
    # RemovedInDjango20Warning: Add template_dirs for compatibility with
    # old loaders
    if func_supports_parameter(self.get_template_sources, 'template_dirs'):
        args.append(template_dirs)

    return_value = None
    return_value_origin = None
    for origin in self.get_template_sources(*args):
        if skip is not None and origin in skip:
            tried.append((origin, 'Skipped'))
            continue

        try:
            contents = self.get_contents(origin)
        except TemplateDoesNotExist:
            tried.append((origin, 'Source does not exist'))
            continue
        else:
            if return_value is None:
                return_value = Template(
                    contents, origin, origin.template_name, self.engine,
                )
                return_value_origin = origin
            else:
                print((
                    "CONFLICT[%s]: %s is used instead of %s"
                    % (return_value_origin.template_name, return_value_origin, origin)
                ))

    if return_value:
        return return_value

    raise TemplateDoesNotExist(template_name, tried=tried)
Пример #29
0
    def render(self, name, value=None, attrs=None, renderer=None):
        json_value = value

        if json_value is None or json_value is '':
            value = None
        else:
            if isinstance(json_value, DraftText):
                json_value = json_value.get_json()
            try:
                value = json.loads(json_value)
            except (ValueError, TypeError):
                value = {}
                logging.getLogger(__name__).warn(
                    'Cannot handle {} as JSON'.format(json_value))

        encoded_value = json.dumps(value)

        parent = super(DraftailTextArea, self)

        if func_supports_parameter(parent.render,
                                   'renderer'):  # >= Django 1.11
            return parent.render(name, encoded_value, attrs, renderer)
        else:
            return parent.render(name, encoded_value, attrs)
Пример #30
0
"""
Пример #31
0
import datetime
Пример #32
0
from django.utils.datastructures import (CaseInsensitiveMapping, ImmutableList,
                                         MultiValueDict)
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain
from django.utils.inspect import func_supports_parameter
from django.utils.regex_helper import _lazy_re_compile

from .multipartparser import parse_header

# TODO: Remove when dropping support for PY37. inspect.signature() is used to
# detect whether the max_num_fields argument is available as this security fix
# was backported to Python 3.6.8 and 3.7.2, and may also have been applied by
# downstream package maintainers to other versions in their repositories.
if (not func_supports_parameter(parse_qsl, 'max_num_fields')
        or not func_supports_parameter(parse_qsl, 'separator')):
    from django.utils.http import parse_qsl

RAISE_ERROR = object()
host_validation_re = _lazy_re_compile(
    r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")


class UnreadablePostError(OSError):
    pass


class RawPostDataException(Exception):
    """
    You cannot access raw_post_data from a request that has
Пример #33
0
import errno
Пример #34
0
def constant_time_compare(val1, val2):
    """Return True if the two strings are equal, False otherwise."""
    return secrets.compare_digest(force_bytes(val1), force_bytes(val2))


def pbkdf2(password, salt, iterations, dklen=0, digest=None):
    """Return the hash of password using pbkdf2."""
    if digest is None:
        digest = hashlib.sha256
    dklen = dklen or None
    password = force_bytes(password)
    salt = force_bytes(salt)
    return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations,
                               dklen)


# TODO: Remove when dropping support for PY38. inspect.signature() is used to
# detect whether the usedforsecurity argument is available as this fix may also
# have been applied by downstream package maintainers to other versions in
# their repositories.
if func_supports_parameter(hashlib.md5, 'usedforsecurity'):
    md5 = hashlib.md5
    new_hash = hashlib.new
else:

    def md5(data=b'', *, usedforsecurity=True):
        return hashlib.md5(data)

    def new_hash(hash_algorithm, *, usedforsecurity=True):
        return hashlib.new(hash_algorithm)
Пример #35
0
    MultiValueDict,
)
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain
from django.utils.inspect import func_supports_parameter
from django.utils.regex_helper import _lazy_re_compile

from .multipartparser import parse_header

# TODO: Remove when dropping support for PY37. inspect.signature() is used to
# detect whether the max_num_fields argument is available as this security fix
# was backported to Python 3.6.8 and 3.7.2, and may also have been applied by
# downstream package maintainers to other versions in their repositories.
if func_supports_parameter(parse_qsl, 'max_num_fields'):
    from django.utils.http import parse_qsl

RAISE_ERROR = object()
host_validation_re = _lazy_re_compile(
    r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")


class UnreadablePostError(OSError):
    pass


class RawPostDataException(Exception):
    """
    You cannot access raw_post_data from a request that has
    multipart/* POST data if it has been accessed via POST,
Пример #36
0
        with connection.cursor() as cursor:
            cursor.execute("SELECT cache_key, value, expires FROM %s "
                           "WHERE cache_key = %%s" % table, [key])
            row = cursor.fetchone()
        if row is None:
            return default

        expires = row[2]
        expression = models.Expression(output_field=models.DateTimeField())
        for converter in (connection.ops.get_db_converters(expression) +
                          expression.get_db_converters(connection)):
<<<<<<< HEAD
            expires = converter(expires, expression, connection, {})
=======
            if func_supports_parameter(converter, 'context'):  # RemovedInDjango30Warning
                expires = converter(expires, expression, connection, {})
            else:
                expires = converter(expires, expression, connection)
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435

        if expires < timezone.now():
            db = router.db_for_write(self.cache_model_class)
            connection = connections[db]
            with connection.cursor() as cursor:
                cursor.execute("DELETE FROM %s "
                               "WHERE cache_key = %%s" % table, [key])
            return default

        value = connection.ops.process_clob(row[1])
        return pickle.loads(base64.b64decode(force_bytes(value)))