avro-python3 序列化与反序列化

5 篇文章 0 订阅

AVRO是由apache出品的一种数据序列化方式,官网:http://avro.apache.org/docs/1.8.2/gettingstartedpython.html

Python版的二进制数据序列化示例如下所示:

# -*- coding: utf-8 -*-

import os
from io import BytesIO

import avro.schema
from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder


class AvroUtils(object):
    """avro序列化接口
    """

    REQUEST_SCHEMA = {}
    RESPONSE_SCHEMA = {}
    ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    REQUEST_AVSC = os.path.join(ROOT_PATH, 'avro_schema', 'retrieve_request.avsc')
    RESPONSE_AVSC = os.path.join(ROOT_PATH, 'avro_schema', 'retrieve_response.avsc')

    @classmethod
    def init_schma(cls, request_file='', response_file=''):
        request_file = request_file or cls.REQUEST_AVSC
        response_file = response_file or cls.RESPONSE_AVSC

        if os.path.exists(request_file) is False:
            raise Exception('File {} is not Exist!'.format(request_file))
        if os.path.exists(response_file) is False:
            raise Exception('File {} is not Exist!'.format(response_file))

        with open(request_file, 'r') as fp:
            cls.REQUEST_SCHEMA = avro.schema.Parse(fp.read())
        with open(response_file, 'r') as fp:
            cls.RESPONSE_SCHEMA = avro.schema.Parse(fp.read())

    @classmethod
    def avro_encode(cls, json_data, schema=None):
        """avro 序列化json数据为二进制

        :param json_data:
        :param schema:
        :return:
        """
        bio = BytesIO()
        binary_encoder = BinaryEncoder(bio)
        dw = DatumWriter(writer_schema=schema or cls.RESPONSE_SCHEMA)
        dw.write(json_data, binary_encoder)
        return bio.getvalue()

    @classmethod
    def avro_decode(cls, binary_data, schema=None):
        """avro 反序列化二进制数据为json

        :param binary_data:
        :param schema:
        :return:
        """
        bio = BytesIO(binary_data)
        binary_decoder = BinaryDecoder(bio)
        return DatumReader(writer_schema=schema or cls.REQUEST_SCHEMA).read(binary_decoder)



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值