django.utils.encoding.force_bytes

Here are the examples of the python api django.utils.encoding.force_bytes taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: GAE-Bulk-Mailer
Source File: client.py
View license
    def write(self, content):
        if self.read_started:
            raise ValueError("Unable to write a payload after he's been read")
        content = force_bytes(content)
        self.__content.write(content)
        self.__len += len(content)

Example 2

Project: GAE-Bulk-Mailer
Source File: cache.py
View license
def _generate_cache_key(request, method, headerlist, key_prefix):
    """Returns a cache key from the headers given in the header list."""
    ctx = hashlib.md5()
    for header in headerlist:
        value = request.META.get(header, None)
        if value is not None:
            ctx.update(force_bytes(value))
    path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, method, path.hexdigest(), ctx.hexdigest())
    return _i18n_cache_key_suffix(request, cache_key)

Example 3

Project: Misago
Source File: views.py
View license
def get_parsed_content(request, setting_name):
    cache_name = 'misago_legal_%s' % setting_name
    cached_content = cache.get(cache_name)

    unparsed_content = settings.get_lazy_setting(setting_name)

    checksum_source = force_bytes('%s:%s' % (unparsed_content, settings.SECRET_KEY))
    unparsed_checksum = md5(checksum_source).hexdigest()

    if cached_content and cached_content.get('checksum') == unparsed_checksum:
        return cached_content['parsed']
    else:
        parsed = common_flavour(request, None, unparsed_content)['parsed_text']
        cached_content = {
            'checksum': unparsed_checksum,
            'parsed': parsed,
        }
        cache.set(cache_name, cached_content)
        return cached_content['parsed']

Example 4

Project: Misago
Source File: credentialchange.py
View license
def _make_change_token(user, token_type):
    seeds = (
        user.pk,
        user.email,
        user.password,
        user.last_login.replace(microsecond=0, tzinfo=None),
        settings.SECRET_KEY,
        six.text_type(token_type)
    )

    return sha256(
        force_bytes('+'.join([six.text_type(s) for s in seeds]))).hexdigest()

Example 5

Project: Misago
Source File: tokens.py
View license
def make(user, token_type):
    user_hash = _make_hash(user, token_type)
    creation_day = _days_since_epoch()

    obfuscated = base64.b64encode(force_bytes('%s%s' % (user_hash, creation_day))).decode()
    obfuscated = obfuscated.rstrip('=')
    checksum = _make_checksum(obfuscated)

    return '%s%s' % (checksum, obfuscated)

Example 6

Project: Misago
Source File: tokens.py
View license
def _make_hash(user, token_type):
    seeds = (
        user.pk,
        user.email,
        user.password,
        user.last_login.replace(microsecond=0, tzinfo=None),
        token_type,
        settings.SECRET_KEY,
    )

    return sha256(force_bytes(
        '+'.join([six.text_type(s) for s in seeds]))).hexdigest()[:8]

Example 7

Project: django-redis-cache
Source File: base_tests.py
View license
    def test_reinsert_keys(self):
        self.cache._pickle_version = 0
        for i in range(2000):
            s = sha1(force_bytes(i)).hexdigest()
            self.cache.set(s, self.cache)
        self.cache._pickle_version = -1
        self.cache.reinsert_keys()

Example 8

Project: callisto-core
Source File: hashers.py
View license
    def split_encoded(self, encoded):
        """
        Splits the encoded string into a separate prefix and stretched key.

        Returns a prefix and a stretched key.
        """
        prefix, b64stretched = encoded.rsplit('$', 1)
        stretched_key = base64.b64decode(b64stretched)
        return prefix, force_bytes(stretched_key)

Example 9

Project: callisto-core
Source File: hashers.py
View license
    def encode(self, key, salt, **kwargs):
        assert key is not None
        assert salt and '$' not in salt
        data = argon2.low_level.hash_secret(
            force_bytes(key),
            force_bytes(salt),
            time_cost=self.time_cost,
            memory_cost=self.memory_cost,
            parallelism=self.parallelism,
            hash_len=32,
            type=argon2.low_level.Type.I,
        )
        return self.algorithm + data.decode('utf-8')

Example 10

Project: callisto-core
Source File: hashers.py
View license
    def verify(self, key, encoded):
        algorithm, rest = encoded.split('$', 1)
        assert algorithm == self.algorithm
        try:
            return argon2.low_level.verify_secret(
                force_bytes('$' + rest),
                force_bytes(key),
                type=argon2.low_level.Type.I,
            )
        except argon2.exceptions.VerificationError:
            return False

Example 11

Project: callisto-core
Source File: test_hashers.py
View license
    def test_encode_returns_correct_prefix(self):
        encoded = self.hasher.encode("this is definitely a key", "also here is a salt")
        prefix = encoded.rsplit('$', 1)[0]
        b64_salt = base64.b64encode(force_bytes("also here is a salt")).decode('utf-8').rstrip('=')
        expected = "argon2$argon2i$v=19$m=512,t=2,p=2${0}".format(b64_salt)
        self.assertEqual(prefix, expected)

Example 12

Project: django-jython
Source File: creation.py
View license
def truncate_name(name, length=None, hash_len=4):
    """
    Shortens a string to a repeatable mangled version with the given length.
    """
    if length is None or len(name) <= length:
        return name

    hsh = hashlib.md5(force_bytes(name)).hexdigest()[:hash_len]
    return '%s%s' % (name[:length - hash_len], hsh)

Example 13

Project: taiga-back
Source File: files.py
View license
def get_file_path(instance, filename, base_path):
    basename = path.basename(filename).lower()
    base, ext = path.splitext(basename)
    base = slugify(unidecode(base))[0:100]
    basename = "".join([base, ext])

    hs = hashlib.sha256()
    hs.update(force_bytes(timezone.now().isoformat()))
    hs.update(urandom(1024))

    p1, p2, p3, p4, *p5 = split_by_n(hs.hexdigest(), 1)
    hash_part = path.join(p1, p2, p3, p4, "".join(p5))

    return path.join(base_path, hash_part, basename)

Example 14

Project: taiga-back
Source File: service.py
View license
def cache_by_sha(func):
    @functools.wraps(func)
    def _decorator(project, text):
        sha1_hash = hashlib.sha1(force_bytes(text)).hexdigest()
        key = "{}-{}".format(sha1_hash, project.id)

        # Try to get it from the cache
        cached = cache.get(key)
        if cached is not None:
            return cached

        returned_value = func(project, text)
        cache.set(key, returned_value, timeout=None)
        return returned_value

    return _decorator

Example 15

Project: gallery
Source File: tests.py
View license
    def test_invalid(self):
        """
        Test that non matching passwords will be caught.
        """
        token = default_token_generator.make_token(self.user)
        uid = urlsafe_base64_encode(force_bytes(self.user.pk))
        url = reverse(
            'accounts:password_reset_confirm',
            kwargs=dict(uid36=uid, token=token))
        self.form_in_response(url)
        form_data = {'new_password1': 'password1',
                     'new_password2': 'password2'}
        response = self.client.post(url, form_data)
        self.assertFormError(
            response, 'form', 'new_password2',
            SetPasswordForm.error_messages['password_mismatch'])

Example 16

Project: gallery
Source File: tests.py
View license
    def test_valid(self):
        """
        Test that matching passwords will be saved.
        """
        token = default_token_generator.make_token(self.user)
        uid = urlsafe_base64_encode(force_bytes(self.user.pk))
        url = reverse(
            'accounts:password_reset_confirm',
            kwargs=dict(uid36=uid, token=token))
        self.form_in_response(url)
        form_data = {'new_password1': 'newpass', 'new_password2': 'newpass'}
        response = self.client.post(url, form_data)
        self.assertRedirects(response, reverse('accounts:login'))

Example 17

Project: gallery
Source File: tests.py
View license
    def test_tampered(self):
        """
        Test that a tampered token or uid will not process.
        """
        urlname = 'accounts:password_reset_confirm'

        # invalid uid, valid token
        uid = 'invalid'
        token = default_token_generator.make_token(self.user)
        url = reverse(urlname, kwargs=dict(uid36=uid, token=token))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

        # valid uid, invalid token
        uid = urlsafe_base64_encode(force_bytes(self.user.pk))
        token = 'not-valid-token'
        url = reverse(urlname, kwargs=dict(uid36=uid, token=token))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)

Example 18

Project: django-rest-auth
Source File: test_api.py
View license
    def _generate_uid_and_token(self, user):
        result = {}
        from django.utils.encoding import force_bytes
        from django.contrib.auth.tokens import default_token_generator
        from django.utils.http import urlsafe_base64_encode

        result['uid'] = urlsafe_base64_encode(force_bytes(user.pk))
        result['token'] = default_token_generator.make_token(user)
        return result

Example 19

Project: django-rest-framework
Source File: test.py
View license
    def get(self, path, data=None, **extra):
        r = {
            'QUERY_STRING': urlencode(data or {}, doseq=True),
        }
        if not data and '?' in path:
            # Fix to support old behavior where you have the arguments in the
            # url. See #1461.
            query_string = force_bytes(path.split('?')[1])
            if six.PY3:
                query_string = query_string.decode('iso-8859-1')
            r['QUERY_STRING'] = query_string
        r.update(extra)
        return self.generic('GET', path, **r)

Example 20

Project: django-tenants
Source File: template_loaders.py
View license
    @staticmethod
    def cache_key(template_name, template_dirs):
        if connection.tenant and template_dirs:
            return '-'.join([str(connection.tenant.pk), template_name,
                             hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            return '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
        else:
            return template_name

Example 21

Project: wagtail
Source File: test_account_management.py
View license
    def setup_password_reset_confirm_tests(self):
        from django.utils.encoding import force_bytes
        from django.utils.http import urlsafe_base64_encode

        # Get user
        self.user = get_user_model().objects.get(username='test')

        # Generate a password reset token
        self.password_reset_token = PasswordResetTokenGenerator().make_token(self.user)

        # Generate a password reset uid
        self.password_reset_uid = urlsafe_base64_encode(force_bytes(self.user.pk))

        # Create url_args
        self.url_kwargs = dict(uidb64=self.password_reset_uid, token=self.password_reset_token)

Example 22

Project: django-downloadview
Source File: io.py
View license
    def _read1(self, n=None):
        while not self._left:
            try:
                self._left = next(self._iter)
            except StopIteration:
                break
            else:
                # Make sure we handle text.
                self._left = force_bytes(self._left)
        ret = self._left[:n]
        self._left = self._left[len(ret):]
        return ret

Example 23

Project: django-adv-cache-tag
Source File: tag.py
View license
    def hash_args(self):
        """
        Take all the arguments passed after the fragment name and return a
        hashed version which will be used in the cache key
        """
        return hashlib.md5(force_bytes(':'.join([urlquote(var) for var in self.vary_on]))).hexdigest()

Example 24

Project: django-adv-cache-tag
Source File: tag.py
View license
    def join_content_version(self, to_cache):
        """
        Add the version(s) to the content to cache : internal version at first
        and then the template version if versioning is activated.
        Each version, and the content, are separated with `VERSION_SEPARATOR`.
        This method is called after the encoding (if "compress" or
        "compress_spaces" options are on)
        """
        parts = [self.INTERNAL_VERSION]
        if self.options.versioning:
            parts.append(force_bytes(self.version))
        parts.append(force_bytes(to_cache))

        return self.VERSION_SEPARATOR.join(parts)

Example 25

Project: django-adv-cache-tag
Source File: tests.py
View license
    @staticmethod
    def get_template_key(fragment_name, vary_on=None, prefix='template.cache'):
        """Compose the cache key of a template."""
        if vary_on is None:
            vary_on = ()
        key = ':'.join([urlquote(var) for var in vary_on])
        args = hashlib.md5(force_bytes(key))
        return (prefix + '.%s.%s') % (fragment_name, args.hexdigest())

Example 26

View license
    @staticmethod
    def cache_key(template_name, template_dirs):
        if connection.tenant and template_dirs:
            return '-'.join([str(connection.tenant.pk), template_name,
                             hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            return '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
        else:
            return template_name

Example 27

Project: wger
Source File: cache.py
View license
def get_template_cache_name(fragment_name='', *args):
    '''
    Logic to calculate the cache key name when using django's template cache.
    Code taken from django/templatetags/cache.py
    '''
    key = u':'.join([str(arg) for arg in args])
    key_name = hashlib.md5(force_bytes(key)).hexdigest()
    return 'template.cache.{0}.{1}'.format(fragment_name, key_name)

Example 28

Project: wger
Source File: helpers.py
View license
def make_uid(input):
    '''
    Small wrapper to generate a UID, usually used in URLs to allow for
    anonymous access
    '''
    return urlsafe_base64_encode(force_bytes(input))

Example 29

Project: django-happenings
Source File: test_ordering.py
View license
    def assertContentBefore(self, response, text1, text2):
        """
        Testing utility asserting that text1 appears before text2 in response
        content. Modified from:
        https://github.com/django/django/blob/master/tests/admin_views/tests.py
        """
        failing_msg = "%s not found before %s" % (text1, text2)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(
            response.content.index(force_bytes(text1)) <
            response.content.index(force_bytes(text2)),
            failing_msg)

Example 30

View license
    def write(self, content):
        if 'w' not in self._mode:
            raise AliyunOperationError("Operation write is not allowed.")

        self.file.write(force_bytes(content))
        self._is_dirty = True
        self._is_read = True

Example 31

Project: django-mysql
Source File: cache.py
View license
    def decode(self, value, value_type):
        """
        Take a value blob and its value_type one-char code and convert it back
        to a python object
        """
        if value_type == 'i':
            return int(value)

        if value_type == 'z':
            value = zlib.decompress(value)
            value_type = 'p'

        if value_type == 'p':
            return pickle.loads(force_bytes(value))

        raise ValueError(
            "Unknown value_type '{}' read from the cache table."
            .format(value_type)
        )

Example 32

Project: decode-Django
Source File: layer.py
View license
    def test_capability(self, capability):
        """
        Returns a bool indicating whether the this Layer supports the given
        capability (a string).  Valid capability strings include:
          'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
          'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
          'DeleteFeature', and 'FastSetNextByIndex'.
        """
        return bool(capi.test_capability(self.ptr, force_bytes(capability)))

Example 33

Project: decode-Django
Source File: srs.py
View license
    def attr_value(self, target, index=0):
        """
        The attribute value for the given target node (e.g. 'PROJCS'). The index
        keyword specifies an index of the child node to return.
        """
        if not isinstance(target, six.string_types) or not isinstance(index, int):
            raise TypeError
        return capi.get_attr_value(self.ptr, force_bytes(target), index)

Example 34

Project: netbox
Source File: models.py
View license
    def get_master_key(self, private_key):
        """
        Given the User's private key, return the encrypted master key.
        """
        if not self.is_active:
            raise ValueError("Unable to retrieve master key: UserKey is inactive.")
        try:
            return decrypt_master_key(force_bytes(self.master_key_cipher), private_key)
        except ValueError:
            return None

Example 35

Project: django-extensions
Source File: modelviz.py
View license
    def get_appmodel_context(self, appmodel, appmodel_abstracts):
        context = {
            'app_name': appmodel.__module__.replace(".", "_"),
            'name': appmodel.__name__,
            'abstracts': appmodel_abstracts,
            'fields': [],
            'relations': []
        }

        if self.verbose_names and appmodel._meta.verbose_name:
            context['label'] = force_bytes(appmodel._meta.verbose_name)
        else:
            context['label'] = context['name']

        return context

Example 36

View license
def dump_json(data):
    '''
    Converts a Python object to a JSON formatted string.
    '''

    json_kwargs = {
        'sort_keys': True,
        'indent': 4,
        'separators': (', ', ': ')
    }

    return force_bytes(json.dumps(data, **json_kwargs))

Example 37

Project: django-oscar
Source File: utils.py
View license
def get_password_reset_url(user, token_generator=default_token_generator):
    """
    Generate a password-reset URL for a given user
    """
    kwargs = {
        'token': token_generator.make_token(user),
        'uidb64': urlsafe_base64_encode(force_bytes(user.id)),
    }
    return reverse('password-reset-confirm', kwargs=kwargs)

Example 38

Project: django-newsletter
Source File: utils.py
View license
def make_activation_code():
    """ Generate a unique activation code. """
    random_string = str(random.random())
    random_digest = sha1(force_bytes(random_string)).hexdigest()[:5]
    time_string = str(datetime.now().microsecond)

    combined_string = random_digest + time_string

    return sha1(force_bytes(combined_string)).hexdigest()

Example 39

Project: wechat-python-sdk
Source File: base.py
View license
    def decode(self, context_data):
        encoded_data = base64.b64decode(force_bytes(context_data))
        try:
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousOpenID('Context data corrupted')
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # TODO: logger
            return {}

Example 40

Project: django-machina
Source File: test_models.py
View license
    def test_objects_know_their_filenames(self):
        # Setup
        f = SimpleUploadedFile('dummy_file.txt', force_bytes('file_content'))
        attachment = AttachmentFactory.create(post=self.post, file=f)
        # Run & check
        assert attachment.filename == 'dummy_file.txt'
        attachment.file.delete()

Example 41

Project: django-s3-storage
Source File: storage.py
View license
    @contextmanager
    def _conditional_convert_content_to_bytes(self, name, content):
        """
        Forces the given text-mode file into a bytes-mode file.
        """
        if isinstance(content.file, TextIOBase):
            with self._temporary_file() as temp_file:
                for chunk in content.chunks():
                    temp_file.write(force_bytes(chunk))
                temp_file.seek(0)
                yield File(temp_file, name)
                return
        yield content

Example 42

Project: django-s3-storage
Source File: tests.py
View license
    def testSaveTextModeFile(self):
        upload_path = self.generateUploadPath()
        file_contents = "Fôö"  # Note the accents. This is a unicode string.
        self.storage.save(upload_path, ContentFile(file_contents, upload_path))
        try:
            stored_contents = self.storage.open(upload_path).read()
            self.assertEqual(stored_contents, force_bytes(file_contents))
        finally:
            self.storage.delete(upload_path)

Example 43

Project: django-s3-storage
Source File: tests.py
View license
    def testSmallGzippedFile(self):
        # A tiny file gets bigger when gzipped.
        upload_path = self.generateUploadPath()
        file_contents = force_bytes(uuid.uuid4().hex, "ascii")
        self.saveTestFile(upload_path, file=ContentFile(file_contents))
        try:
            self.assertTrue(self.storage.exists(upload_path))
            # Generate a URL.
            url = self.storage.url(upload_path)
            # Ensure that the URL is accessible.
            self.assertUrlAccessible(url, file_contents=file_contents, content_encoding=None)
        finally:
            # Clean up the test file.
            self.storage.delete(upload_path)

Example 44

Project: django-blog-zinnia
Source File: markups.py
View license
def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS):
    """
    RestructuredText processing with optionnally custom settings.
    """
    try:
        from docutils.core import publish_parts
    except ImportError:
        warnings.warn("The Python docutils library isn't installed.",
                      RuntimeWarning)
        return value

    parts = publish_parts(source=force_bytes(value),
                          writer_name='html4css1',
                          settings_overrides=settings)
    return force_text(parts['fragment'])

Example 45

Project: django-widgy
Source File: models.py
View license
def friendly_uuid(uuid):
    """
    A shortend version of a UUID to use when collisions are acceptable.
    The returned string will have 40 bits of entropy assuming a UUID4.
    """
    result = base64.b32encode(hashlib.sha1(force_bytes(uuid)).digest()[:5]).lower()
    unicode_result = result.decode('ascii')
    # avoid accidental profanity
    profanity_filter = (unicode_result.replace('e', '0')
                                      .replace('o', '1')
                                      .replace('u', '8')
                                      .replace('i', '9'))
    return profanity_filter

Example 46

Project: django-cryptography
Source File: conf.py
View license
    def configure(self):
        backend = self.configured_data['BACKEND']
        digest = self.configured_data['DIGEST']
        salt = self.configured_data['SALT']
        # Key Derivation Function
        kdf = pbkdf2.PBKDF2HMAC(
            algorithm=digest,
            length=digest.digest_size,
            salt=salt,
            iterations=30000,
            backend=backend,
        )
        self.configured_data['KEY'] = kdf.derive(
            force_bytes(self.configured_data['KEY'] or settings.SECRET_KEY)
        )
        return self.configured_data

Example 47

Project: django-cryptography
Source File: crypto.py
View license
def constant_time_compare(val1, val2):
    """
    :type val1: any
    :type val2: any
    :rtype: bool
    """
    return constant_time.bytes_eq(force_bytes(val1), force_bytes(val2))

Example 48

Project: django-cryptography
Source File: crypto.py
View license
    def encrypt(self, data):
        """
        :type data: any
        :rtype: any
        """
        data = force_bytes(data)
        iv = os.urandom(16)
        return self._encrypt_from_parts(data, iv)

Example 49

Project: sentry
Source File: s3.py
View license
    def _compress_content(self, content):
        """Gzip a given string content."""
        zbuf = BytesIO()
        zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
        try:
            zfile.write(force_bytes(content.read()))
        finally:
            zfile.close()
        zbuf.seek(0)
        # Boto 2 returned the InMemoryUploadedFile with the file pointer replaced,
        # but Boto 3 seems to have issues with that. No need for fp.name in Boto3
        # so just returning the BytesIO directly
        return zbuf

Example 50

Project: sentry
Source File: organizationmember.py
View license
    @property
    def legacy_token(self):
        checksum = md5()
        checksum.update(six.text_type(self.organization_id).encode('utf-8'))
        checksum.update(self.get_email().encode('utf-8'))
        checksum.update(force_bytes(settings.SECRET_KEY))
        return checksum.hexdigest()