使用Avro将对象编码为Python中的字节数组

Gra*_*rby 13 python-2.7 avro

在python 2.7中,使用Avro,我想将一个对象编码为一个字节数组.

我发现的所有示例都写入文件.

我尝试过使用io.BytesIO(),但这给出了:

AttributeError: '_io.BytesIO' object has no attribute 'write_long'
Run Code Online (Sandbox Code Playgroud)

使用io.BytesIO的示例

def avro_encode(raw, schema):
    writer = DatumWriter(schema)
    avro_buffer = io.BytesIO()
    writer.write(raw, avro_buffer)
    return avro_buffer.getvalue()
Run Code Online (Sandbox Code Playgroud)

ppe*_*rcy 32

你的问题帮我解决了问题,谢谢.这是一个基于文档中的python示例的简单python示例:

import io
import avro.schema
import avro.io

test_schema = '''
{
"namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "favorite_number",  "type": ["int", "null"]},
     {"name": "favorite_color", "type": ["string", "null"]}
 ]
}
'''

schema = avro.schema.parse(test_schema)
writer = avro.io.DatumWriter(schema)

bytes_writer = io.BytesIO()
encoder = avro.io.BinaryEncoder(bytes_writer)
writer.write({"name": "Alyssa", "favorite_number": 256}, encoder)
writer.write({"name": "Ben", "favorite_number": 7, "favorite_color": "red"}, encoder)

raw_bytes = bytes_writer.getvalue()
print(len(raw_bytes))
print(type(raw_bytes))

bytes_reader = io.BytesIO(raw_bytes)
decoder = avro.io.BinaryDecoder(bytes_reader)
reader = avro.io.DatumReader(schema)
user1 = reader.read(decoder)
user2 = reader.read(decoder)

print(user1)
print(user2)
Run Code Online (Sandbox Code Playgroud)

  • 如果要在Python 3下运行,请将“ schema = avro.schema.parse(test_schema)”更改为“ schema = avro.schema.Parse(test_schema)” (3认同)