-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathproperties.py
268 lines (203 loc) · 8.56 KB
/
properties.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from dataclasses import dataclass, field
from typing import Any, ClassVar, Dict, List, Optional
from .reference import Reference
@dataclass
class Property:
""" Describes a single property for a schema """
name: str
required: bool
default: Optional[Any]
constructor_template: ClassVar[Optional[str]] = None
_type_string: ClassVar[str]
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self._type_string
return f"Optional[{self._type_string}]"
def to_string(self) -> str:
""" How this should be declared in a dataclass """
if self.default:
default = self.default
elif not self.required:
default = "None"
else:
default = None
if default is not None:
return f"{self.name}: {self.get_type_string()} = {self.default}"
else:
return f"{self.name}: {self.get_type_string()}"
def transform(self) -> str:
""" What it takes to turn this object into a native python type """
return self.name
def constructor_from_dict(self, dict_name: str) -> str:
""" How to load this property from a dict (used in generated model from_dict function """
if self.required:
return f'{dict_name}["{self.name}"]'
else:
return f'{dict_name}.get("{self.name}")'
@dataclass
class StringProperty(Property):
""" A property of type str """
max_length: Optional[int] = None
pattern: Optional[str] = None
_type_string: ClassVar[str] = "str"
def __post_init__(self) -> None:
if self.default is not None:
self.default = f'"{self.default}"'
@dataclass
class DateTimeProperty(Property):
""" A property of type datetime.datetime """
_type_string: ClassVar[str] = "datetime"
constructor_template: ClassVar[str] = "datetime_property.pyi"
@dataclass
class FloatProperty(Property):
""" A property of type float """
default: Optional[float] = None
_type_string: ClassVar[str] = "float"
@dataclass
class IntProperty(Property):
""" A property of type int """
default: Optional[int] = None
_type_string: ClassVar[str] = "int"
@dataclass
class BooleanProperty(Property):
""" Property for bool """
_type_string: ClassVar[str] = "bool"
@dataclass
class BasicListProperty(Property):
""" A List of basic types """
type: str
def constructor_from_dict(self, dict_name: str) -> str:
""" How to set this property from a dictionary of values """
return f'{dict_name}.get("{self.name}", [])'
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return f"List[{self.type}]"
return f"Optional[List[{self.type}]]"
@dataclass
class ReferenceListProperty(Property):
""" A List of References """
reference: Reference
constructor_template: ClassVar[str] = "reference_list_property.pyi"
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return f"List[{self.reference.class_name}]"
return f"Optional[List[{self.reference.class_name}]]"
@dataclass
class EnumListProperty(Property):
""" List of Enum values """
values: Dict[str, str]
reference: Reference = field(init=False)
constructor_template: ClassVar[str] = "enum_list_property.pyi"
def __post_init__(self) -> None:
self.reference = Reference.from_ref(self.name)
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return f"List[{self.reference.class_name}]"
return f"Optional[List[{self.reference.class_name}]]"
@dataclass
class EnumProperty(Property):
""" A property that should use an enum """
values: Dict[str, str]
reference: Reference = field(init=False)
def __post_init__(self) -> None:
self.reference = Reference.from_ref(self.name)
inverse_values = {v: k for k, v in self.values.items()}
if self.default is not None:
self.default = f"{self.reference.class_name}.{inverse_values[self.default]}"
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self.reference.class_name
return f"Optional[{self.reference.class_name}]"
def transform(self) -> str:
""" Output to the template, convert this Enum into a JSONable value """
return f"{self.name}.value"
def constructor_from_dict(self, dict_name: str) -> str:
""" How to load this property from a dict (used in generated model from_dict function """
constructor = f'{self.reference.class_name}({dict_name}["{self.name}"])'
if not self.required:
constructor += f' if "{self.name}" in {dict_name} else None'
return constructor
@staticmethod
def values_from_list(l: List[str], /) -> Dict[str, str]:
""" Convert a list of values into dict of {name: value} """
output: Dict[str, str] = {}
for i, value in enumerate(l):
if value[0].isalpha():
key = value.upper()
else:
key = f"VALUE_{i}"
assert key not in output, f"Duplicate key {key} in Enum"
output[key] = value
return output
@dataclass
class RefProperty(Property):
""" A property which refers to another Schema """
reference: Reference
constructor_template: ClassVar[str] = "ref_property.pyi"
def get_type_string(self) -> str:
""" Get a string representation of type that should be used when declaring this property """
if self.required:
return self.reference.class_name
return f"Optional[{self.reference.class_name}]"
def transform(self) -> str:
""" Convert this into a JSONable value """
return f"{self.name}.to_dict()"
@dataclass
class DictProperty(Property):
""" Property that is a general Dict """
_type_string: ClassVar[str] = "Dict[Any, Any]"
_openapi_types_to_python_type_strings = {
"string": "str",
"number": "float",
"integer": "int",
"boolean": "bool",
"object": "Dict[Any, Any]",
}
def property_from_dict(name: str, required: bool, data: Dict[str, Any]) -> Property:
""" Generate a Property from the OpenAPI dictionary representation of it """
if "enum" in data:
return EnumProperty(
name=name,
required=required,
values=EnumProperty.values_from_list(data["enum"]),
default=data.get("default"),
)
if "$ref" in data:
return RefProperty(name=name, required=required, reference=Reference.from_ref(data["$ref"]), default=None)
if data["type"] == "string":
if "format" not in data:
return StringProperty(
name=name, default=data.get("default"), required=required, pattern=data.get("pattern"),
)
elif data["format"] == "date-time":
return DateTimeProperty(name=name, required=required, default=data.get("default"))
elif data["type"] == "number":
return FloatProperty(name=name, default=data.get("default"), required=required)
elif data["type"] == "integer":
return IntProperty(name=name, default=data.get("default"), required=required)
elif data["type"] == "boolean":
return BooleanProperty(name=name, required=required, default=data.get("default"))
elif data["type"] == "array":
if "$ref" in data["items"]:
return ReferenceListProperty(
name=name, required=required, default=None, reference=Reference.from_ref(data["items"]["$ref"])
)
if "enum" in data["items"]:
return EnumListProperty(
name=name, required=required, default=None, values=EnumProperty.values_from_list(data["items"]["enum"])
)
if "type" in data["items"]:
return BasicListProperty(
name=name,
required=required,
default=None,
type=_openapi_types_to_python_type_strings[data["items"]["type"]],
)
elif data["type"] == "object":
return DictProperty(name=name, required=required, default=data.get("default"))
raise ValueError(f"Did not recognize type of {data}")