当前位置: 首页>>代码示例>>Python>>正文


Python encoding.force_bytes方法代码示例

本文整理汇总了Python中django.utils.encoding.force_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python encoding.force_bytes方法的具体用法?Python encoding.force_bytes怎么用?Python encoding.force_bytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.encoding的用法示例。


在下文中一共展示了encoding.force_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: validate_and_return_id_token

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def validate_and_return_id_token(jws, nonce=None, validate_nonce=True):
    """ Validates the id_token according to the OpenID Connect specification. """
    shared_key = oidc_rp_settings.CLIENT_SECRET \
        if oidc_rp_settings.PROVIDER_SIGNATURE_ALG == 'HS256' \
        else oidc_rp_settings.PROVIDER_SIGNATURE_KEY  # RS256

    try:
        # Decodes the JSON Web Token and raise an error if the signature is invalid.
        id_token = JWS().verify_compact(force_bytes(jws), _get_jwks_keys(shared_key))
    except JWKESTException:
        return

    # Validates the claims embedded in the id_token.
    _validate_claims(id_token, nonce=nonce, validate_nonce=validate_nonce)

    return id_token 
开发者ID:impak-finance,项目名称:django-oidc-rp,代码行数:18,代码来源:utils.py

示例2: salted_hmac

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:25,代码来源:crypto.py

示例3: encode_file

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def encode_file(boundary, key, file):
    to_bytes = lambda s: force_bytes(s, settings.DEFAULT_CHARSET)
    filename = os.path.basename(file.name) if hasattr(file, 'name') else ''
    if hasattr(file, 'content_type'):
        content_type = file.content_type
    elif filename:
        content_type = mimetypes.guess_type(filename)[0]
    else:
        content_type = None

    if content_type is None:
        content_type = 'application/octet-stream'
    if not filename:
        filename = key
    return [
        to_bytes('--%s' % boundary),
        to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
                 % (key, filename)),
        to_bytes('Content-Type: %s' % content_type),
        b'',
        to_bytes(file.read())
    ] 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:24,代码来源:client.py

示例4: decode

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def decode(self, session_data):
        encoded_data = base64.b64decode(force_bytes(session_data))
        try:
            # could produce ValueError if there is no ':'
            hash, serialized = encoded_data.split(b':', 1)
            expected_hash = self._hash(serialized)
            if not constant_time_compare(hash.decode(), expected_hash):
                raise SuspiciousSession("Session data corrupted")
            else:
                return self.serializer().loads(serialized)
        except Exception as e:
            # ValueError, SuspiciousOperation, unpickling exceptions. If any of
            # these happen, just return an empty dictionary (an empty session).
            if isinstance(e, SuspiciousOperation):
                logger = logging.getLogger('django.security.%s' %
                        e.__class__.__name__)
                logger.warning(force_text(e))
            return {} 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:base.py

示例5: encode

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def encode(self, password, salt):
        bcrypt = self._load_library()
        # Need to reevaluate the force_bytes call once bcrypt is supported on
        # Python 3

        # Hash the password prior to using bcrypt to prevent password truncation
        #   See: https://code.djangoproject.com/ticket/20138
        if self.digest is not None:
            # We use binascii.hexlify here because Python3 decided that a hex encoded
            #   bytestring is somehow a unicode.
            password = binascii.hexlify(self.digest(force_bytes(password)).digest())
        else:
            password = force_bytes(password)

        data = bcrypt.hashpw(password, salt)
        return "%s$%s" % (self.algorithm, force_text(data)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:hashers.py

示例6: verify

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def verify(self, password, encoded):
        algorithm, data = encoded.split('$', 1)
        assert algorithm == self.algorithm
        bcrypt = self._load_library()

        # Hash the password prior to using bcrypt to prevent password truncation
        #   See: https://code.djangoproject.com/ticket/20138
        if self.digest is not None:
            # We use binascii.hexlify here because Python3 decided that a hex encoded
            #   bytestring is somehow a unicode.
            password = binascii.hexlify(self.digest(force_bytes(password)).digest())
        else:
            password = force_bytes(password)

        # Ensure that our data is a bytestring
        data = force_bytes(data)
        # force_bytes() necessary for py-bcrypt compatibility
        hashpw = force_bytes(bcrypt.hashpw(password, data))

        return constant_time_compare(data, hashpw) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:hashers.py

示例7: groups_for_user

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def groups_for_user(environ, username):
    """
    Authorizes a user based on groups
    """

    UserModel = auth.get_user_model()
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:modwsgi.py

示例8: _check_query

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def _check_query(self, query, country=False, city=False, city_or_country=False):
        "Helper routine for checking the query and database availability."
        # Making sure a string was passed in for the query.
        if not isinstance(query, six.string_types):
            raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)

        # Extra checks for the existence of country and city databases.
        if city_or_country and not (self._country or self._city):
            raise GeoIPException('Invalid GeoIP country and city data files.')
        elif country and not self._country:
            raise GeoIPException('Invalid GeoIP country data file: %s' % self._country_file)
        elif city and not self._city:
            raise GeoIPException('Invalid GeoIP city data file: %s' % self._city_file)

        # Return the query string back to the caller. GeoIP only takes bytestrings.
        return force_bytes(query) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:18,代码来源:base.py

示例9: loads

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
    """
    Reverse of dumps(), raises BadSignature if signature fails.

    The serializer is expected to accept a bytestring.
    """
    # TimestampSigner.unsign always returns unicode but base64 and zlib
    # compression operate on bytes.
    base64d = force_bytes(TimestampSigner(key, salt=salt).unsign(s, max_age=max_age))
    decompress = False
    if base64d[:1] == b'.':
        # It's compressed; uncompress it first
        base64d = base64d[1:]
        decompress = True
    data = b64_decode(base64d)
    if decompress:
        data = zlib.decompress(data)
    return serializer().loads(data) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:signing.py

示例10: pbkdf2

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
    """
    Implements PBKDF2 with the same API as Django's existing
    implementation, using cryptography.

    :type password: any
    :type salt: any
    :type iterations: int
    :type dklen: int
    :type digest: cryptography.hazmat.primitives.hashes.HashAlgorithm
    """
    if digest is None:
        digest = settings.CRYPTOGRAPHY_DIGEST
    if not dklen:
        dklen = digest.digest_size
    password = force_bytes(password)
    salt = force_bytes(salt)
    kdf = PBKDF2HMAC(
        algorithm=digest,
        length=dklen,
        salt=salt,
        iterations=iterations,
        backend=settings.CRYPTOGRAPHY_BACKEND)
    return kdf.derive(password) 
开发者ID:georgemarshall,项目名称:django-cryptography,代码行数:26,代码来源:crypto.py

示例11: loads

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def loads(s,
          key=None,
          salt='django.core.signing',
          serializer=JSONSerializer,
          max_age=None):
    """
    Reverse of dumps(), raises BadSignature if signature fails.

    The serializer is expected to accept a bytestring.
    """
    # TimestampSigner.unsign always returns unicode but base64 and zlib
    # compression operate on bytes.
    base64d = force_bytes(
        TimestampSigner(key, salt=salt).unsign(s, max_age=max_age))
    decompress = False
    if base64d[:1] == b'.':
        # It's compressed; uncompress it first
        base64d = base64d[1:]
        decompress = True
    data = b64_decode(base64d)
    if decompress:
        data = zlib.decompress(data)
    return serializer().loads(data) 
开发者ID:georgemarshall,项目名称:django-cryptography,代码行数:25,代码来源:signing.py

示例12: get_password_reset_email

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def get_password_reset_email(user, reset_url,
                             subject_template_name='registration/password_reset_subject.txt',  # noqa
                             email_template_name='api_password_reset_email.html',  # noqa
                             token_generator=default_token_generator):
    """Creates the subject and email body for password reset email."""
    result = urlparse(reset_url)
    site_name = domain = result.hostname
    c = {
        'email': user.email,
        'domain': domain,
        'path': result.path,
        'site_name': site_name,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'username': user.username,
        'encoded_username': urlsafe_base64_encode(user.username),
        'token': token_generator.make_token(user),
        'protocol': result.scheme if result.scheme != '' else 'http',
    }
    subject = loader.render_to_string(subject_template_name, c)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    email = loader.render_to_string(email_template_name, c)

    return subject, email 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:26,代码来源:password_reset_serializer.py

示例13: test_reset_user_password

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def test_reset_user_password(self):
        # set user.last_login, ensures we get same/valid token
        # https://code.djangoproject.com/ticket/10265
        self.user.last_login = now()
        self.user.save()
        token = default_token_generator.make_token(self.user)
        new_password = "bobbob1"
        data = {'token': token, 'new_password': new_password}
        # missing uid, should fail
        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 400)

        data['uid'] = urlsafe_base64_encode(force_bytes(self.user.pk))
        # with uid, should be successful
        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 204)
        user = User.objects.get(email=self.user.email)
        self.assertTrue(user.check_password(new_password))

        request = self.factory.post('/', data=data)
        response = self.view(request)
        self.assertEqual(response.status_code, 400) 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:26,代码来源:test_connect_viewset.py

示例14: salted_hmac

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def salted_hmac(key_salt, value, secret=None):
    """
    Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    key = hashlib.sha1(key_salt + secret).digest()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:25,代码来源:crypto.py

示例15: make_bytes

# 需要导入模块: from django.utils import encoding [as 别名]
# 或者: from django.utils.encoding import force_bytes [as 别名]
def make_bytes(self, value):
        """Turn a value into a bytestring encoded in the output charset."""
        # Per PEP 3333, this response body must be bytes. To avoid returning
        # an instance of a subclass, this function returns `bytes(value)`.
        # This doesn't make a copy when `value` already contains bytes.

        # Handle string types -- we can't rely on force_bytes here because:
        # - Python attempts str conversion first
        # - when self._charset != 'utf-8' it re-encodes the content
        if isinstance(value, bytes):
            return bytes(value)
        if isinstance(value, str):
            return bytes(value.encode(self.charset))

        # Handle non-string types (#16494)
        return force_bytes(value, self.charset)

    # These methods partially implement the file-like object interface.
    # See https://docs.python.org/3/library/io.html#io.IOBase

    # The WSGI server must call this method upon completion of the request.
    # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:24,代码来源:response.py


注:本文中的django.utils.encoding.force_bytes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。