I am both a Python and Avro novice and struggled with the example code for 
Python at 
https://avro.apache.org/docs/1.11.1/getting-started-python/#serializing-and-deserializing-without-code-generation.

Slightly modified code worked well for me. So requesting if someone seconds my 
opinion to update Python code at the website (could not find a way to self-help 
or recommend changes). Thanks in anticipation.

# Note the required import is 1.1x avro and not avro-python3
from avro import (
    schema,
    io,
    datafile
)

# Pass schema as string
user_schema = schema.parse(open("user.avsc", "rb").read().decode())

writer = datafile.DataFileWriter(open("users.avro", "wb"), io.DatumWriter(), 
user_schema)
writer.append({"name": "Alyssa", "favorite_number": 256})
writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"})
writer.close()

reader = datafile.DataFileReader(open("users.avro", "rb"), io.DatumReader())
for user in reader:
    print(user)
reader.close()

Reply via email to