-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathschema.py
More file actions
55 lines (44 loc) · 1.68 KB
/
schema.py
File metadata and controls
55 lines (44 loc) · 1.68 KB
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
from typing import Dict
from jsonschema_gentypes.cli import process_config
from jsonschema_gentypes import configuration
import tempfile
import json
def _cleanup_input_for_gentypes(input_data: Dict):
""" cleanup input_data in place to make it more suitable for jsonschema_gentypes
"""
for k, v in input_data.items():
if isinstance(v, dict):
_cleanup_input_for_gentypes(v)
elif k == "enum":
# jsonschema_gentypes doesn't like double quotes in enums
# TODO fix this upstream
for idx, enum in enumerate(v):
assert isinstance(enum, str)
v[idx] = enum.replace('"', "'")
def _temp_store_input_data(input_data: Dict) -> str:
"""take in the input data and store it in a temporary json file"""
with tempfile.NamedTemporaryFile(
mode="w", delete=False, prefix="polyapi_", suffix=".json"
) as temp_file:
json.dump(input_data, temp_file)
return temp_file.name
def generate_schema_types(input_data: Dict):
"""takes in a Dict representing a schema as input then appends the resulting python code to the output file"""
_cleanup_input_for_gentypes(input_data)
tmp_input = _temp_store_input_data(input_data)
tmp_output = tempfile.NamedTemporaryFile(
mode="w", delete=False, prefix="polyapi_", suffix=".json"
).name
config: configuration.Configuration = {
"python_version": None, # type: ignore
"generate": [
{
"source": tmp_input,
"destination": tmp_output,
}
],
}
process_config(config)
with open(tmp_output) as f:
output = f.read()
return output