Skip to content

Commit 4ca8355

Browse files
committed
Initial commit
1 parent 66cc033 commit 4ca8355

File tree

11 files changed

+338
-0
lines changed

11 files changed

+338
-0
lines changed

.gitignore

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
98+
__pypackages__/
99+
100+
# Celery stuff
101+
celerybeat-schedule
102+
celerybeat.pid
103+
104+
# SageMath parsed files
105+
*.sage.py
106+
107+
# Environments
108+
.env
109+
.venv
110+
env/
111+
venv/
112+
ENV/
113+
env.bak/
114+
venv.bak/
115+
116+
# Spyder project settings
117+
.spyderproject
118+
.spyproject
119+
120+
# Rope project settings
121+
.ropeproject
122+
123+
# mkdocs documentation
124+
/site
125+
126+
# mypy
127+
.mypy_cache/
128+
.dmypy.json
129+
dmypy.json
130+
131+
# Pyre type checker
132+
.pyre/
133+
134+
# pytype static type analyzer
135+
.pytype/
136+
137+
# Cython debug symbols
138+
cython_debug/
139+
140+
# my stuff
141+
.idea
142+
.private.txt

LICENSE.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright (c) 2020 Phillip Dupuis
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pydantic2ts/__init__.py

Whitespace-only changes.

pydantic2ts/cli/__init__.py

Whitespace-only changes.

pydantic2ts/cli/script.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import click
2+
import inspect
3+
import importlib
4+
import os
5+
import shutil
6+
from pydantic import BaseModel, create_model
7+
from typing import Type, Dict, Any
8+
from types import ModuleType
9+
10+
11+
def remove_property_titles(schema: Dict[str, Any], model: Type[BaseModel]) -> None:
12+
"""
13+
Monkey-patched method for removing titles from JSON schema properties.
14+
If we don't do this, each property will have its own interface in the
15+
resulting typescript file (which is a LOT of unnecessary noise).
16+
"""
17+
for prop in schema.get('properties', {}).values():
18+
prop.pop('title', None)
19+
20+
21+
def extract_pydantic_models(module: ModuleType):
22+
"""
23+
Given a module, return a list of the pydantic models contained within it.
24+
"""
25+
models = []
26+
for name in dir(module):
27+
obj = getattr(module, name)
28+
if (not name.startswith('_'))\
29+
and inspect.isclass(obj)\
30+
and issubclass(obj, BaseModel)\
31+
and obj != BaseModel:
32+
models.append(obj)
33+
return models
34+
35+
36+
def remove_master_model_from_output(output: str) -> None:
37+
"""
38+
A faux 'master model' with references to all the pydantic models is necessary for generating
39+
clean typescript definitions without any duplicates, but we don't actually want it in the
40+
output. This function handles removing it from the generated typescript file.
41+
"""
42+
with open(output, 'r') as f:
43+
lines = f.readlines()
44+
45+
start, end = None, None
46+
for i, line in enumerate(lines):
47+
if line.rstrip('\r\n') == 'export interface _Master_ {':
48+
start = i
49+
elif (start is not None) and line.rstrip('\r\n') == '}':
50+
end = i
51+
break
52+
53+
new_lines = lines[:start] + lines[(end + 1):]
54+
with open(output, 'w') as f:
55+
f.writelines(new_lines)
56+
57+
58+
@click.command()
59+
@click.option('--module')
60+
@click.option('--output')
61+
@click.option('--json2ts-cmd', default='json2ts')
62+
def main(
63+
module: str,
64+
output: str,
65+
json2ts_cmd: str = 'json2ts',
66+
) -> None:
67+
"""
68+
Convert the pydantic models in a python module into typescript interfaces.
69+
70+
:param module: python module containing pydantic model definitions, ex: my_project.api.schemas
71+
:param output: file that the typescript definitions will be written to
72+
:param json2ts_cmd: optional, the command that will execute json2ts. Use this if it's installed in a strange spot.
73+
"""
74+
if not shutil.which(json2ts_cmd):
75+
raise Exception('json2ts must be installed. Instructions can be found here: '
76+
'https://www.npmjs.com/package/json-schema-to-typescript')
77+
78+
models = extract_pydantic_models(importlib.import_module(module))
79+
80+
for m in models:
81+
m.Config.schema_extra = staticmethod(remove_property_titles)
82+
83+
master_model = create_model('_Master_', **{m.__name__: (m, ...) for m in models})
84+
master_model.Config.schema_extra = staticmethod(remove_property_titles)
85+
86+
with open('schema.json', 'w') as f:
87+
f.write(master_model.schema_json(indent=2))
88+
89+
banner_comment = '\n'.join([
90+
'/* tslint:disable */',
91+
'/**',
92+
'/* This file was automatically generated from pydantic models by running pydantic2ts.',
93+
'/* Do not modify it by hand - just update the pydantic models and then re-run the script',
94+
'*/',
95+
])
96+
97+
os.system(f'{json2ts_cmd} -i schema.json -o {output} --bannerComment "{banner_comment}"')
98+
os.remove('schema.json')
99+
remove_master_model_from_output(output)
100+
101+
102+
if __name__ == '__main__':
103+
main()

pydantic2ts/examples/__init__.py

Whitespace-only changes.

pydantic2ts/examples/convert.sh

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/bash
2+
3+
pydantic2ts --module pydantic2ts.examples.pydantic_models --output output.ts

pydantic2ts/examples/output.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/* tslint:disable */
2+
/**
3+
/* This file was automatically generated from pydantic models by running pydantic2ts.
4+
/* Do not modify it by hand - just update the pydantic models and then re-run the script
5+
*/
6+
7+
export interface Athlete {
8+
name: string;
9+
age: number;
10+
sports: ("football" | "basketball" | "running" | "swimming")[];
11+
}
12+
export interface Team {
13+
name: string;
14+
sport: "football" | "basketball" | "running" | "swimming";
15+
athletes: Athlete[];
16+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from pydantic import BaseModel, Extra
2+
from enum import Enum
3+
from typing import List
4+
5+
6+
class NoUnspecifiedProps:
7+
extra = Extra.forbid
8+
9+
10+
class Sport(str, Enum):
11+
football = 'football'
12+
basketball = 'basketball'
13+
running = 'running'
14+
swimming = 'swimming'
15+
16+
17+
class Athlete(BaseModel):
18+
name: str
19+
age: int
20+
sports: List[Sport]
21+
Config = NoUnspecifiedProps
22+
23+
24+
class Team(BaseModel):
25+
name: str
26+
sport: Sport
27+
athletes: List[Athlete]
28+
Config = NoUnspecifiedProps

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
click
2+
pydantic

0 commit comments

Comments
 (0)