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


Python compat.bytes_函数代码示例

本文整理汇总了Python中pyramid.compat.bytes_函数的典型用法代码示例。如果您正苦于以下问题:Python bytes_函数的具体用法?Python bytes_怎么用?Python bytes_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: check_csrf_token

def check_csrf_token(request,
                     token='csrf_token',
                     header='X-CSRF-Token',
                     raises=True):
    """ Check the CSRF token in the request's session against the value in
    ``request.params.get(token)`` or ``request.headers.get(header)``.
    If a ``token`` keyword is not supplied to this function, the string
    ``csrf_token`` will be used to look up the token in ``request.params``.
    If a ``header`` keyword is not supplied to this function, the string
    ``X-CSRF-Token`` will be used to look up the token in ``request.headers``.

    If the value supplied by param or by header doesn't match the value
    supplied by ``request.session.get_csrf_token()``, and ``raises`` is
    ``True``, this function will raise an
    :exc:`pyramid.exceptions.BadCSRFToken` exception.
    If the check does succeed and ``raises`` is ``False``, this
    function will return ``False``.  If the CSRF check is successful, this
    function will return ``True`` unconditionally.

    Note that using this function requires that a :term:`session factory` is
    configured.

    .. versionadded:: 1.4a2
    """
    supplied_token = request.params.get(token, request.headers.get(header, ""))
    expected_token = request.session.get_csrf_token()
    if strings_differ(bytes_(expected_token), bytes_(supplied_token)):
        if raises:
            raise BadCSRFToken('check_csrf_token(): Invalid token')
        return False
    return True
开发者ID:Chris-May,项目名称:pyramid,代码行数:31,代码来源:session.py

示例2: test_blob

    def test_blob(self):
        import ptah.cms

        blob = ptah.cms.blob_storage.add(BytesIO(bytes_('blob data','utf-8')))
        self.assertTrue(ptah.cms.IBlob.providedBy(blob))
        self.assertEqual(blob.read(), bytes_('blob data','utf-8'))
        self.assertTrue(ptah.cms.IBlobStorage.providedBy(ptah.cms.blob_storage))
开发者ID:runyaga,项目名称:ptah,代码行数:7,代码来源:test_blobstorage.py

示例3: oauth_response

def oauth_response(result):
    headers, body, status = result
    return Response(body=body, status=status, headers={
        bytes_(name, 'utf-8'): bytes_(value, 'utf-8')
        for name, value
        in headers.iteritems()
    })
开发者ID:gutomaia,项目名称:pyramid-oauthlib,代码行数:7,代码来源:__init__.py

示例4: pbkdf2_bin

def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`.  It iterates `iterations` time and produces a
    key of `keylen` bytes.  By default SHA-1 is used as hash function,
    a different hashlib `hashfunc` can be provided.
    """
    hashfunc = hashfunc or hashlib.sha1
    mac = hmac.new(bytes_(data), None, hashfunc)

    def _pseudorandom(x, mac=mac):
        h = mac.copy()
        h.update(bytes_(x))
        if PY3:  # pragma: no cover
            return [x for x in h.digest()]
        else:  # pragma: no cover
            return map(ord, h.digest())
    buf = []
    for block in range_(1, -(-keylen // mac.digest_size) + 1):
        rv = u = _pseudorandom(bytes_(salt) + _pack_int(block))
        for i in range_(iterations - 1):
            if PY3:  # pragma: no cover
                u = _pseudorandom(bytes(u))
            else:  # pragma: no cover
                u = _pseudorandom(''.join(map(chr, u)))
            rv = starmap(xor, zip(rv, u))
        buf.extend(rv)
    if PY3:  # pragma: no cover
        return bytes(buf)[:keylen]
    else:  # pragma: no cover
        return ''.join(map(chr, buf))[:keylen]
开发者ID:joshfinnie,项目名称:lumin,代码行数:30,代码来源:pbkdf2.py

示例5: signed_deserialize

def signed_deserialize(serialized, secret, hmac=hmac):
    """ Deserialize the value returned from ``signed_serialize``.  If
    the value cannot be deserialized for any reason, a
    :exc:`ValueError` exception will be raised.

    This function is useful for deserializing a signed cookie value
    created by ``signed_serialize``.  For example:

    .. code-block:: python

       cookieval = request.cookies['signed_cookie']
       data = signed_deserialize(cookieval, 'secret')
    """
    # hmac parameterized only for unit tests
    try:
        input_sig, pickled = (serialized[:40],
                              base64.b64decode(bytes_(serialized[40:])))
    except (binascii.Error, TypeError) as e:
        # Badly formed data can make base64 die
        raise ValueError('Badly formed base64 data: %s' % e)

    sig = hmac.new(bytes_(secret), pickled, sha1).hexdigest()

    # Avoid timing attacks (see
    # http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf)
    if strings_differ(sig, input_sig):
        raise ValueError('Invalid signature')

    return pickle.loads(pickled)
开发者ID:AdamG,项目名称:pyramid,代码行数:29,代码来源:session.py

示例6: unsign_session_id

def unsign_session_id(cookie, secret):
    cookie = bytes_(cookie)
    input_sig, session_id = (cookie[:32], cookie[32:])
    sig = hmac.new(bytes_(secret), session_id, sha1).digest()

    # Avoid timing attacks (see
    # http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf)
    if strings_differ(base64.b32encode(sig), input_sig):
        raise ValueError('Invalid signature')
    return session_id
开发者ID:0x1997,项目名称:pyramid_redis_sessions,代码行数:10,代码来源:util.py

示例7: calculate_digest

def calculate_digest(ip, timestamp, secret, userid, tokens, user_data):
    secret = bytes_(secret, 'utf-8')
    userid = bytes_(userid, 'utf-8')
    tokens = bytes_(tokens, 'utf-8')
    user_data = bytes_(user_data, 'utf-8')
    digest0 = md5(
        encode_ip_timestamp(ip, timestamp) + secret + userid + b'\0'
        + tokens + b'\0' + user_data).hexdigest()
    digest = md5(bytes_(digest0) + secret).hexdigest()
    return digest
开发者ID:AndreaCrotti,项目名称:pyramid,代码行数:10,代码来源:authentication.py

示例8: test_blob_write

    def test_blob_write(self):
        import ptah

        blob_uri = ptah.cms.blob_storage.add(
            BytesIO(bytes_('blob data','utf-8'))).__uri__
        blob = ptah.resolve(blob_uri)
        blob.write(bytes_('new data','utf-8'))
        transaction.commit()

        blob = ptah.resolve(blob_uri)
        self.assertEqual(blob.read(), bytes_('new data','utf-8'))
开发者ID:runyaga,项目名称:ptah,代码行数:11,代码来源:test_blobstorage.py

示例9: check_csrf_token

def check_csrf_token(request,
                     token='csrf_token',
                     header='X-CSRF-Token',
                     raises=True):
    """ Check the CSRF token in the request's session against the value in
    ``request.POST.get(token)`` (if a POST request) or
    ``request.headers.get(header)``. If a ``token`` keyword is not supplied to
    this function, the string ``csrf_token`` will be used to look up the token
    in ``request.POST``. If a ``header`` keyword is not supplied to this
    function, the string ``X-CSRF-Token`` will be used to look up the token in
    ``request.headers``.

    If the value supplied by post or by header doesn't match the value
    supplied by ``request.session.get_csrf_token()``, and ``raises`` is
    ``True``, this function will raise an
    :exc:`pyramid.exceptions.BadCSRFToken` exception.
    If the values differ and ``raises`` is ``False``, this function will
    return ``False``.  If the CSRF check is successful, this function will
    return ``True`` unconditionally.

    Note that using this function requires that a :term:`session factory` is
    configured.

    See :ref:`auto_csrf_checking` for information about how to secure your
    application automatically against CSRF attacks.

    .. versionadded:: 1.4a2

    .. versionchanged:: 1.7a1
       A CSRF token passed in the query string of the request is no longer
       considered valid. It must be passed in either the request body or
       a header.
    """
    supplied_token = ""
    # If this is a POST/PUT/etc request, then we'll check the body to see if it
    # has a token. We explicitly use request.POST here because CSRF tokens
    # should never appear in an URL as doing so is a security issue. We also
    # explicitly check for request.POST here as we do not support sending form
    # encoded data over anything but a request.POST.
    if token is not None:
        supplied_token = request.POST.get(token, "")

    # If we were unable to locate a CSRF token in a request body, then we'll
    # check to see if there are any headers that have a value for us.
    if supplied_token == "" and header is not None:
        supplied_token = request.headers.get(header, "")

    expected_token = request.session.get_csrf_token()
    if strings_differ(bytes_(expected_token), bytes_(supplied_token)):
        if raises:
            raise BadCSRFToken('check_csrf_token(): Invalid token')
        return False
    return True
开发者ID:MatthewWilkes,项目名称:pyramid,代码行数:53,代码来源:session.py

示例10: test_blob_resolver

    def test_blob_resolver(self):
        import ptahcms

        blob = ptahcms.blob_storage.add(BytesIO(bytes_('blob data','utf-8')))

        blob_uri = blob.__uri__
        transaction.commit()

        blob = ptah.resolve(blob_uri)

        self.assertEqual(blob.__uri__, blob_uri)
        self.assertEqual(blob.read(), bytes_('blob data','utf-8'))
开发者ID:djedproject,项目名称:ptahcms,代码行数:12,代码来源:test_blobstorage.py

示例11: calculate_digest

def calculate_digest(ip, timestamp, secret, userid, tokens, user_data,
                     hashalg='md5'):
    secret = bytes_(secret, 'utf-8')
    userid = bytes_(userid, 'utf-8')
    tokens = bytes_(tokens, 'utf-8')
    user_data = bytes_(user_data, 'utf-8')
    hash_obj = hashlib.new(hashalg)
    hash_obj.update(
        encode_ip_timestamp(ip, timestamp) + secret + userid + b'\0'
        + tokens + b'\0' + user_data)
    digest = hash_obj.hexdigest()
    hash_obj2 = hashlib.new(hashalg)
    hash_obj2.update(bytes_(digest) + secret)
    return hash_obj2.hexdigest()
开发者ID:Airwalker1337,项目名称:pyramid,代码行数:14,代码来源:authentication.py

示例12: test_blob_rest_data

    def test_blob_rest_data(self):
        import ptah.cms
        from ptah.cms.rest import blobData

        blob = ptah.cms.blob_storage.add(
            BytesIO(bytes_('blob data','utf-8')),
            filename='test.txt', mimetype='text/plain')

        response = blobData(blob, self.request)
        self.assertEqual(response.body, bytes_('blob data','utf-8'))
        self.assertEqual(
            response.headerlist,
            [('Content-Disposition', bytes_('filename="test.txt"','utf-8')),
             ('Content-Length', '9')])
开发者ID:runyaga,项目名称:ptah,代码行数:14,代码来源:test_blobstorage.py

示例13: test_password_ssha

    def test_password_ssha(self):
        from ptah.password import SSHAPasswordManager

        manager = SSHAPasswordManager()

        password = text_("right А", 'utf-8')
        encoded = manager.encode(password, salt=bytes_("",'utf-8'))

        self.assertEqual(
            encoded, bytes_('{ssha}BLTuxxVMXzouxtKVb7gLgNxzdAI=','ascii'))
        self.assertTrue(manager.check(encoded, password))
        self.assertFalse(manager.check(encoded, password + "wrong"))

        encoded = manager.encode(password)
        self.assertTrue(manager.check(encoded, password))
开发者ID:rainerwahnsinn,项目名称:ptah,代码行数:15,代码来源:test_password.py

示例14: forbidden_view

def forbidden_view(context, request):
    msg = context.message
    result = context.result
    message = msg + "\n" + str(result)
    resp = HTTPForbidden()
    resp.body = bytes_(message)
    return resp
开发者ID:replaceafill,项目名称:pyramid,代码行数:7,代码来源:__init__.py

示例15: make_param_predicates

def make_param_predicates(param_type, param, params_attr,
                          weights, weight, predicates, hash):
    if not is_nonstr_iter(param):
        param = (param,)
    param = sorted(param)
    text = "%s_param %r" % (param_type, param)
    reqs = []
    for p in param:
        pair = p.split('=', 1)
        if len(pair) == 1:
            pair = pair+[None]
        reqs.append(pair)
    if len(reqs) == 1 and reqs[0][1] is None:
        text = "%s_param %s" % (param_type, param[0])
    def param_predicate(context, request):
        params = getattr(request, params_attr)
        for k, v in reqs:
            if v is None:
                return k in params
            if params.get(k) != v:
                return False
        return True
    param_predicate.__text__ = text
    weights.append(1 << weight)
    predicates.append(param_predicate)
    for p in param:
        hash.update(bytes_('%s_param:%r' % (param_type, p)))
开发者ID:rpatterson,项目名称:pyramid,代码行数:27,代码来源:util.py


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