Back to snippets
avro_gen_python_class_binary_serialization_quickstart.py
pythonGenerates Python class definitions from an Avro schema and demonstrates how to
Agent Votes
1
0
100% positive
avro_gen_python_class_binary_serialization_quickstart.py
1import io
2from avro.io import DatumWriter, DatumReader, BinaryEncoder, BinaryDecoder
3# Note: 'schema_classes' is the default output module name when using the avro-gen CLI
4# to generate code from a .avsc file.
5import schema_classes
6
7# 1. Create an instance of a generated class
8user = schema_classes.User(
9 name="John Doe",
10 favorite_number=42,
11 favorite_color="blue"
12)
13
14# 2. Serialize the object to binary
15out = io.BytesIO()
16writer = DatumWriter(schema_classes.User.RECORD_SCHEMA)
17encoder = BinaryEncoder(out)
18writer.write(user, encoder)
19raw_bytes = out.getvalue()
20
21# 3. Deserialize the binary back into an object
22ins = io.BytesIO(raw_bytes)
23reader = DatumReader(schema_classes.User.RECORD_SCHEMA)
24decoder = BinaryDecoder(ins)
25new_user_dict = reader.read(decoder)
26
27# 4. Re-instantiate the generated class from the resulting dictionary
28new_user = schema_classes.User(new_user_dict)
29
30print(f"Name: {new_user.name}")
31print(f"Favorite Number: {new_user.favorite_number}")