pydantic-avro 0.8.1__tar.gz → 0.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pydantic-avro
3
- Version: 0.8.1
3
+ Version: 0.9.0
4
4
  Summary: Converting pydantic classes to avro schemas
5
5
  Home-page: https://github.com/godatadriven/pydantic-avro
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "pydantic-avro"
3
- version = "0.8.1"
3
+ version = "0.9.0"
4
4
  description = "Converting pydantic classes to avro schemas"
5
5
  authors = ["Peter van 't Hof' <peter.vanthof@godatadriven.com>"]
6
6
 
@@ -18,7 +18,7 @@ entry_points = \
18
18
 
19
19
  setup_kwargs = {
20
20
  'name': 'pydantic-avro',
21
- 'version': '0.8.1',
21
+ 'version': '0.9.0',
22
22
  'description': 'Converting pydantic classes to avro schemas',
23
23
  'long_description': '[![Python package](https://github.com/godatadriven/pydantic-avro/actions/workflows/python-package.yml/badge.svg)](https://github.com/godatadriven/pydantic-avro/actions/workflows/python-package.yml)\n[![codecov](https://codecov.io/gh/godatadriven/pydantic-avro/branch/main/graph/badge.svg?token=5L08GOERAW)](https://codecov.io/gh/godatadriven/pydantic-avro)\n[![PyPI version](https://badge.fury.io/py/pydantic-avro.svg)](https://badge.fury.io/py/pydantic-avro)\n[![CodeQL](https://github.com/godatadriven/pydantic-avro/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/godatadriven/pydantic-avro/actions/workflows/codeql-analysis.yml)\n\n# pydantic-avro\n\nThis library can convert a pydantic class to a avro schema or generate python code from a avro schema.\n\n### Install\n\n```bash\npip install pydantic-avro\n```\n\n### Pydantic class to avro schema\n\n```python\nimport json\nfrom typing import Optional\n\nfrom pydantic_avro.base import AvroBase\n\n\nclass TestModel(AvroBase):\n key1: str\n key2: int\n key2: Optional[str]\n\n\nschema_dict: dict = TestModel.avro_schema()\nprint(json.dumps(schema_dict))\n\n```\n\n### Avro schema to pydantic\n\n```shell\n# Print to stdout\npydantic-avro avro_to_pydantic --asvc /path/to/schema.asvc\n\n# Save it to a file\npydantic-avro avro_to_pydantic --asvc /path/to/schema.asvc --output /path/to/output.py\n```\n\n### Specify expected Avro type\n\n```python\nfrom datetime import datetime\nfrom pydantic import Field\nfrom pydantic_avro.base import AvroBase \n\nclass ExampleModel(AvroBase):\n field1: int = Field(..., avro_type="long") # Explicitly set Avro type to "long"\n field2: datetime = Field(..., avro_type="timestamp-millis") # Explicitly set Avro type to "timestamp-millis"\n```\n\n### Install for developers\n\n###### Install package\n\n- Requirement: Poetry 1.*\n\n```shell\npoetry install\n```\n\n###### Run unit tests\n```shell\npytest\ncoverage run -m pytest # with coverage\n# or (depends on your local env) \npoetry run pytest\npoetry run coverage run -m pytest # with coverage\n```\n\n##### Run linting\n\nThe linting is checked in the github workflow. To fix and review issues run this:\n```shell\nblack . # Auto fix all issues\nisort . # Auto fix all issues\npflake . # Only display issues, fixing is manual\n```\n',
24
24
  'author': "Peter van 't Hof'",
@@ -61,6 +61,8 @@ AVRO_TYPE_MAPPING = {
61
61
  },
62
62
  }
63
63
 
64
+ PRIMITVE_TYPES = ["int", "long", "float", "double", "boolean", "null"]
65
+
64
66
 
65
67
  def get_definition(ref: str, schema: dict):
66
68
  """Reading definition of base schema for nested structs"""
@@ -133,6 +135,9 @@ class AvroTypeConverter:
133
135
  at = field_props.get("avro_type")
134
136
  if "allOf" in field_props and len(field_props["allOf"]) == 1:
135
137
  r = field_props["allOf"][0]["$ref"]
138
+ if ("prefixItems" in field_props or ("minItems" in field_props and "maxItems" in field_props)) and t == "array":
139
+ t = "tuple"
140
+
136
141
  u = field_props.get("anyOf")
137
142
 
138
143
  if u is not None:
@@ -162,6 +167,8 @@ class AvroTypeConverter:
162
167
  avro_type_dict["type"] = "boolean"
163
168
  elif t == "null":
164
169
  avro_type_dict["type"] = "null"
170
+ elif t == "tuple":
171
+ return self._tuple_to_avro(field_props, avro_type_dict)
165
172
  else:
166
173
  raise NotImplementedError(
167
174
  f"Type '{t}' not support yet, "
@@ -216,7 +223,10 @@ class AvroTypeConverter:
216
223
  def _object_to_avro(self, field_props: dict) -> dict:
217
224
  """Returns a type of an object field"""
218
225
  a = field_props.get("additionalProperties")
219
- value_type = "string" if a is None else self._get_avro_type_dict(a)["type"]
226
+ if not a or isinstance(a, bool):
227
+ value_type = "string"
228
+ else:
229
+ value_type = self._get_avro_type_dict(a)["type"]
220
230
  return {"type": "map", "values": value_type}
221
231
 
222
232
  def _union_to_avro(self, field_props: list, avro_type_dict: dict) -> dict:
@@ -227,23 +237,43 @@ class AvroTypeConverter:
227
237
  avro_type_dict["type"].append(t["type"])
228
238
  return avro_type_dict
229
239
 
240
+ def _tuple_to_avro(self, field_props: dict, avro_type_dict: dict) -> dict:
241
+ """Returns a type of a tuple field"""
242
+ prefix_items = field_props.get("prefixItems")
243
+ if not prefix_items:
244
+ # Pydantic v1 there is no prefixItems, but minItems and maxItems and items is a list.
245
+ prefix_items = field_props.get("items")
246
+ if not prefix_items:
247
+ raise ValueError(f"Tuple Field '{field_props}' does not have any items .")
248
+ possible_types = []
249
+ for prefix_item in prefix_items:
250
+ item_type = self._get_avro_type(prefix_item, avro_type_dict).get("type")
251
+ if not item_type:
252
+ raise ValueError(f"Field '{avro_type_dict}' does not have a defined type.")
253
+ if isinstance(item_type, list):
254
+ possible_types.extend([x for x in item_type if x not in possible_types])
255
+ elif item_type not in possible_types:
256
+ possible_types.append(item_type)
257
+ avro_type_dict["type"] = {"type": "array", "items": possible_types}
258
+ return avro_type_dict
259
+
230
260
  def _array_to_avro(self, field_props: dict, avro_type_dict: dict) -> dict:
231
261
  """Returns a type of an array field"""
232
- items = field_props["items"]
262
+ items = field_props.get("items")
263
+ # In pydantic v1. items is a list, we need to handle this case first
264
+ # E.g. [{'type': 'number'}, {'type': 'number'}]}
265
+ if isinstance(items, list):
266
+ if not len(items):
267
+ raise ValueError(f"Field '{field_props}' does not have valid items.")
268
+ items = items[0]
269
+ if not isinstance(items, dict):
270
+ raise ValueError(f"Field '{field_props}' does not have valid items.")
233
271
  tn = self._get_avro_type_dict(items)
234
272
  # If items in array are an object:
235
273
  if "$ref" in items:
236
274
  tn = tn["type"]
237
275
  # If items in array are a logicalType
238
- if (
239
- isinstance(tn, dict)
240
- and isinstance(tn.get("type", {}), dict)
241
- and tn.get("type", {}).get("logicalType") is not None
242
- ):
276
+ if isinstance(tn, dict) and isinstance(tn.get("type", None), (dict, list)):
243
277
  tn = tn["type"]
244
- # If items in array are an array, the structure must be corrected
245
- if isinstance(tn, dict) and isinstance(tn.get("type", {}), dict) and tn.get("type", {}).get("type") == "array":
246
- items = tn["type"]["items"]
247
- tn = {"type": "array", "items": items}
248
278
  avro_type_dict["type"] = {"type": "array", "items": tn}
249
279
  return avro_type_dict
File without changes
File without changes