Debian Codegraph @

doc/content/en/docs/++version++/Getting started (Python)/_index.md

raw
1 ---
2 categories: []
3 tags: ["python"]
4 title: "Getting Started (Python)"
5 linkTitle: "Getting Started (Python)"
6 weight: 3
7 aliases:
8 - /docs/current/getting-started-python/
9 ---
10
11 <!--
12
13 Licensed to the Apache Software Foundation (ASF) under one
14 or more contributor license agreements. See the NOTICE file
15 distributed with this work for additional information
16 regarding copyright ownership. The ASF licenses this file
17 to you under the Apache License, Version 2.0 (the
18 "License"); you may not use this file except in compliance
19 with the License. You may obtain a copy of the License at
20
21 https://www.apache.org/licenses/LICENSE-2.0
22
23 Unless required by applicable law or agreed to in writing,
24 software distributed under the License is distributed on an
25 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26 KIND, either express or implied. See the License for the
27 specific language governing permissions and limitations
28 under the License.
29
30 -->
31
32 This is a short guide for getting started with Apache Avro™ using Python. This guide only covers using Avro for data serialization; see Patrick Hunt's Avro RPC Quick Start for a good introduction to using Avro for RPC.
33
34 ## Notice for Python 3 users
35 A package called "avro-python3" had been provided to support Python 3 previously, but the codebase was consolidated into the "avro" package and that supports both Python 2 and 3 now. The avro-python3 package will be removed in the near future, so users should use the "avro" package instead. They are mostly API compatible, but there's a few minor difference (e.g., function name capitalization, such as avro.schema.Parse vs avro.schema.parse).
36
37 ## Download
38 For Python, the easiest way to get started is to install it from PyPI. Python's Avro API is available over PyPi.
39
40 ```shell
41 $ python3 -m pip install avro
42 ```
43
44 The official releases of the Avro implementations for C, C++, C#, Java, PHP, Python, and Ruby can be downloaded from the Apache Avro™ Releases page. This guide uses Avro {{< avro_version >}}, the latest version at the time of writing. Download and unzip avro-{{< avro_version >}}.tar.gz, and install via python setup.py (this will probably require root privileges). Ensure that you can import avro from a Python prompt.
45
46 ```shell
47 $ tar xvf avro-{{< avro_version >}}.tar.gz
48 $ cd avro-{{< avro_version >}}
49 $ python setup.py install
50 $ python
51 >>> import avro # should not raise ImportError
52 ```
53
54 Alternatively, you may build the Avro Python library from source. From your the root Avro directory, run the commands
55
56 ```shell
57 $ cd lang/py/
58 $ python3 -m pip install -e .
59 $ python
60 ```
61
62 ## Defining a schema
63 Avro schemas are defined using JSON. Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed). You can learn more about Avro schemas and types from the specification, but for now let's start with a simple schema example, user.avsc:
64
65 ```json
66 {"namespace": "example.avro",
67 "type": "record",
68 "name": "User",
69 "fields": [
70 {"name": "name", "type": "string"},
71 {"name": "favorite_number", "type": ["int", "null"]},
72 {"name": "favorite_color", "type": ["string", "null"]}
73 ]
74 }
75 ```
76
77 This schema defines a record representing a hypothetical user. (Note that a schema file can only contain a single schema definition.) At minimum, a record definition must include its type ("type": "record"), a name ("name": "User"), and fields, in this case name, favorite_number, and favorite_color. We also define a namespace ("namespace": "example.avro"), which together with the name attribute defines the "full name" of the schema (example.avro.User in this case).
78
79 Fields are defined via an array of objects, each of which defines a name and type (other attributes are optional, see the record specification for more details). The type attribute of a field is another schema object, which can be either a primitive or complex type. For example, the name field of our User schema is the primitive type string, whereas the favorite_number and favorite_color fields are both unions, represented by JSON arrays. unions are a complex type that can be any of the types listed in the array; e.g., favorite_number can either be an int or null, essentially making it an optional field.
80
81 ## Serializing and deserializing without code generation
82 Data in Avro is always stored with its corresponding schema, meaning we can always read a serialized item, regardless of whether we know the schema ahead of time. This allows us to perform serialization and deserialization without code generation. Note that the Avro Python library does not support code generation.
83
84 Try running the following code snippet, which serializes two users to a data file on disk, and then reads back and deserializes the data file:
85
86 ```python
87 import avro.schema
88 from avro.datafile import DataFileReader, DataFileWriter
89 from avro.io import DatumReader, DatumWriter
90
91 schema = avro.schema.parse(open("user.avsc", "rb").read())
92
93 writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema)
94 writer.append({"name": "Alyssa", "favorite_number": 256})
95 writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"})
96 writer.close()
97
98 reader = DataFileReader(open("users.avro", "rb"), DatumReader())
99 for user in reader:
100 print(user)
101 reader.close()
102 ```
103
104 This outputs:
105
106 ```json
107 {'favorite_color': None, 'favorite_number': 256, 'name': 'Alyssa'}
108 {'favorite_color': 'red', 'favorite_number': 7, 'name': 'Ben'}
109 ```
110
111 Do make sure that you open your files in binary mode (i.e. using the modes wb or rb respectively). Otherwise you might generate corrupt files due to automatic replacement of newline characters with the platform-specific representations.
112
113 Let's take a closer look at what's going on here.
114
115 ```python
116 schema = avro.schema.parse(open("user.avsc", "rb").read())
117 ```
118
119 avro.schema.parse takes a string containing a JSON schema definition as input and outputs a avro.schema.Schema object (specifically a subclass of Schema, in this case RecordSchema). We're passing in the contents of our user.avsc schema file here.
120
121 ```python
122 writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema)
123 ```
124
125 We create a DataFileWriter, which we'll use to write serialized items to a data file on disk. The DataFileWriter constructor takes three arguments:
126
127 * The file we'll serialize to
128 * A DatumWriter, which is responsible for actually serializing the items to Avro's binary format (DatumWriters can be used separately from DataFileWriters, e.g., to perform IPC with Avro).
129 * The schema we're using. The DataFileWriter needs the schema both to write the schema to the data file, and to verify that the items we write are valid items and write the appropriate fields.
130
131 ```python
132 writer.append({"name": "Alyssa", "favorite_number": 256})
133 writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"})
134 ```
135
136 We use DataFileWriter.append to add items to our data file. Avro records are represented as Python dicts. Since the field favorite_color has type ["string", "null"], we are not required to specify this field, as shown in the first append. Were we to omit the required name field, an exception would be raised. Any extra entries not corresponding to a field are present in the dict are ignored.
137
138 ```python
139 reader = DataFileReader(open("users.avro", "rb"), DatumReader())
140 ```
141
142 We open the file again, this time for reading back from disk. We use a DataFileReader and DatumReader analagous to the DataFileWriter and DatumWriter above.
143
144 ```python
145 for user in reader:
146 print(user)
147 ```
148
149 The DataFileReader is an iterator that returns dicts corresponding to the serialized items.