How to use the cbor2.decoder function in cbor2

To help you get started, we’ve selected a few cbor2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github liberapay / liberapay.com / liberapay / utils / cbor.py View on Github external
def encode_date(encoder, value):
    encode_semantic(encoder, CBORTag(100, value.isoformat()))


def decode_date(decoder, value, shareable_index=None):
    if type(value) == str:
        return date(*map(int, value.split('-')))
    elif type(value) == int:
        return EPOCH + timedelta(days=value)
    else:
        raise TypeError("expected str or int, got %r" % type(value))


cbor2.encoder.default_encoders[date] = encode_date
cbor2.decoder.semantic_decoders[100] = decode_date


# Money and MoneyBasket
# =====================
# Spec: https://liberapay.github.io/specs/cbor-money.html

def encode_Money(encoder, value):
    if set(value.__dict__.keys()) == {'amount', 'currency'}:
        encode_semantic(encoder, CBORTag(77111, '%s%s' % (value.currency, value.amount)))
    else:
        attrs = {
            k: v for k, v in value.__dict__.items()
            if k not in {'amount', 'currency'}
        }
        encode_semantic(encoder, CBORTag(77111, [value.currency, value.amount, attrs]))
github crossbario / autobahn-python / autobahn / xbr / _buyer.py View on Github external
e = self._keys[key_id]
            raise e

        # now that we have the data encryption key, decrypt the application payload
        # the decryption key here is an instance of nacl.secret.SecretBox
        try:
            message = self._keys[key_id].decrypt(ciphertext)
        except nacl.exceptions.CryptoError as e:
            # Decryption failed. Ciphertext failed verification
            raise ApplicationError('xbr.error.decryption_failed', '{}.unwrap() - failed to unwrap encrypted data: {}'.format(self.__class__.__name__, e))

        # deserialize the application payload
        # FIXME: support more app payload serializers
        try:
            payload = cbor2.loads(message)
        except cbor2.decoder.CBORDecodeError as e:
            # premature end of stream (expected to read 4187 bytes, got 27 instead)
            raise ApplicationError('xbr.error.deserialization_failed', '{}.unwrap() - failed to deserialize application payload: {}'.format(self.__class__.__name__, e))

        return payload
github liberapay / liberapay.com / liberapay / utils / cbor.py View on Github external
def decode_MoneyBasket(decoder, value, shareable_index=None):
    r = MoneyBasket()
    r.__dict__.update(value.pop('attrs', ()))
    for k, v in value.items():
        if len(k) == 3 and k.isupper():
            r.amounts[k] = Decimal(v)
        else:
            raise ValueError("key %r is not a currency code" % k)
    return r


cbor2.encoder.default_encoders[Money] = encode_Money
cbor2.encoder.default_encoders[MoneyBasket] = encode_MoneyBasket

cbor2.decoder.semantic_decoders[77111] = decode_Money
cbor2.decoder.semantic_decoders[77112] = decode_MoneyBasket


dumps = cbor2.dumps
loads = cbor2.loads