swaggerspect 0.0.2__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.
- swaggerspect-0.0.2/LICENSE +21 -0
- swaggerspect-0.0.2/PKG-INFO +10 -0
- swaggerspect-0.0.2/README.md +25 -0
- swaggerspect-0.0.2/setup.cfg +4 -0
- swaggerspect-0.0.2/setup.py +18 -0
- swaggerspect-0.0.2/swaggerspect/__init__.py +276 -0
- swaggerspect-0.0.2/swaggerspect.egg-info/PKG-INFO +10 -0
- swaggerspect-0.0.2/swaggerspect.egg-info/SOURCES.txt +9 -0
- swaggerspect-0.0.2/swaggerspect.egg-info/dependency_links.txt +1 -0
- swaggerspect-0.0.2/swaggerspect.egg-info/requires.txt +1 -0
- swaggerspect-0.0.2/swaggerspect.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 EMerald Geomodelling
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: swaggerspect
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Home-page: https://github.com/emerald-geomodelling/swaggerspect
|
|
5
|
+
Author: Egil Moeller
|
|
6
|
+
Author-email: em@emrld.no
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
|
|
10
|
+
Introspects python classes and functions and generates swagger style documentation objects.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Swaggerspect
|
|
2
|
+
|
|
3
|
+
Swaggerspect introspects python classes and functions and generates machine readable descriptions in the [Swagger](https://swagger.io/specification/) and [JSON Schema](https://json-schema.org/) syntaxes.
|
|
4
|
+
Yes, this is an intentional misuse of swagger, as swagger is meant to document REST API:s, not python functions, and to a lesser degree, of JSON Schema.
|
|
5
|
+
|
|
6
|
+
The intended usage is to generate JSON that in turn can be sused to generate a simple user interface for the python functions or classes.
|
|
7
|
+
In particular, this works out of the box with the [json-editor](https://github.com/json-editor/json-editor) web based JSON editor. Note that this library does ot provide any framework to serve REST requests executing the functions in any generate JSON; but that is about 10 lines of code in your favourite web app framework (Django, Flask...).
|
|
8
|
+
|
|
9
|
+
# Usage
|
|
10
|
+
|
|
11
|
+
To get a swagger specification fragment for a single function or class:
|
|
12
|
+
```
|
|
13
|
+
print(yaml.dump(swaggerspect.get_api(some_function_or_class)))
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
To get a full swagger definition for a set of functions and classes, either listed in an entry point group, or available in a single module:
|
|
17
|
+
```
|
|
18
|
+
print(yaml.dump(swaggerspect.get_apis("my.entrypoint.group")))
|
|
19
|
+
print(yaml.dump(swaggerspect.get_apis("some_module_name")))
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The same, but as a JSON schema for a single finction call, or a list of calls (`multi=True`):
|
|
23
|
+
```
|
|
24
|
+
print(yaml.dump(swaggerspect.swagger_to_json_schema(swaggerspect.get_apis("my.entrypoint.group"), multi=False)))
|
|
25
|
+
```
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
import setuptools
|
|
4
|
+
|
|
5
|
+
setuptools.setup(
|
|
6
|
+
name='swaggerspect',
|
|
7
|
+
version='0.0.2',
|
|
8
|
+
description='',
|
|
9
|
+
long_description="""Introspects python classes and functions and generates swagger style documentation objects.""",
|
|
10
|
+
long_description_content_type="text/markdown",
|
|
11
|
+
author='Egil Moeller',
|
|
12
|
+
author_email='em@emrld.no',
|
|
13
|
+
url='https://github.com/emerald-geomodelling/swaggerspect',
|
|
14
|
+
packages=setuptools.find_packages(),
|
|
15
|
+
install_requires=[
|
|
16
|
+
"numpydoc",
|
|
17
|
+
],
|
|
18
|
+
)
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import numpydoc.docscrape
|
|
3
|
+
import ast
|
|
4
|
+
import typing
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
|
|
7
|
+
def _get_name(obj):
|
|
8
|
+
if obj is None: return None
|
|
9
|
+
return obj.__module__ + "." + obj.__name__
|
|
10
|
+
|
|
11
|
+
typemap = {
|
|
12
|
+
'builtins.str': 'string',
|
|
13
|
+
'builtins.int': 'integer',
|
|
14
|
+
'builtins.float': 'number',
|
|
15
|
+
'builtins.bool': 'boolean',
|
|
16
|
+
'builtins.list': 'array',
|
|
17
|
+
'tuple': 'array',
|
|
18
|
+
'str': 'string',
|
|
19
|
+
'int': 'integer',
|
|
20
|
+
'float': 'number',
|
|
21
|
+
'bool': 'boolean',
|
|
22
|
+
'list': 'array',
|
|
23
|
+
'tuple': 'array'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
def typeof(v):
|
|
27
|
+
if v is None: return None
|
|
28
|
+
if v is inspect._empty: return None
|
|
29
|
+
return type(v)
|
|
30
|
+
|
|
31
|
+
def make_type_schema(*typenames):
|
|
32
|
+
for typename in typenames:
|
|
33
|
+
orig = typename
|
|
34
|
+
if typename is inspect._empty:
|
|
35
|
+
continue
|
|
36
|
+
if typename is None:
|
|
37
|
+
continue
|
|
38
|
+
schema = {}
|
|
39
|
+
if not isinstance(typename, str):
|
|
40
|
+
if isinstance(typename, typing._AnnotatedAlias):
|
|
41
|
+
for metadata in typename.__metadata__:
|
|
42
|
+
schema.update({key[len("swaggerspect_"):]: getattr(metadata, key)
|
|
43
|
+
for key in dir(metadata) if key.startswith("swaggerspect_")})
|
|
44
|
+
typename = typename.__args__[0]
|
|
45
|
+
args = typing.get_args(typename)
|
|
46
|
+
typename = _get_name(typename)
|
|
47
|
+
schema["type"] = typemap.get(typename, "object")
|
|
48
|
+
schema["x-python-type"] = typename
|
|
49
|
+
#schema["x-python-orig"] = repr(orig)
|
|
50
|
+
if schema["type"] == "array" and args:
|
|
51
|
+
schema["items"] = make_type_schema(args[0])
|
|
52
|
+
return schema
|
|
53
|
+
return {}
|
|
54
|
+
|
|
55
|
+
def make_value_schema(*values):
|
|
56
|
+
for value in values:
|
|
57
|
+
if value is inspect._empty:
|
|
58
|
+
continue
|
|
59
|
+
if value is None:
|
|
60
|
+
continue
|
|
61
|
+
if isinstance(value, (int, str, dict, list, bool)):
|
|
62
|
+
return {"default": value}
|
|
63
|
+
return {}
|
|
64
|
+
|
|
65
|
+
def _merge_list(a, b):
|
|
66
|
+
akeys = [p["name"] for p in a]
|
|
67
|
+
bkeys = [p["name"] for p in b]
|
|
68
|
+
params = merge({p["name"]: p for p in a}, {p["name"]: p for p in b})
|
|
69
|
+
|
|
70
|
+
return ([params[key] for key in akeys]
|
|
71
|
+
+ [params[key] for key in bkeys if key not in akeys])
|
|
72
|
+
|
|
73
|
+
def merge(a, b):
|
|
74
|
+
if a is None: return b
|
|
75
|
+
if b is None: return a
|
|
76
|
+
if type(a) is not type(b): return a
|
|
77
|
+
if isinstance(a, dict):
|
|
78
|
+
return {k: merge(a.get(k), b.get(k))
|
|
79
|
+
for k in set(a.keys()).union(b.keys())}
|
|
80
|
+
if isinstance(a, list):
|
|
81
|
+
if (a and "name" in a[0]) or (b and "name" in b[0]):
|
|
82
|
+
return _merge_list(a, b)
|
|
83
|
+
return a
|
|
84
|
+
|
|
85
|
+
def remove_empty(obj):
|
|
86
|
+
if not isinstance(obj, dict): return obj
|
|
87
|
+
return {k: v for
|
|
88
|
+
k, v in [(k, remove_empty(v))
|
|
89
|
+
for k, v in obj.items()]
|
|
90
|
+
if v}
|
|
91
|
+
|
|
92
|
+
def _get_class_property_comments(cls):
|
|
93
|
+
propdocs = {}
|
|
94
|
+
for base in cls.__bases__:
|
|
95
|
+
if base is not object:
|
|
96
|
+
propdocs.update(_get_class_property_comments(base))
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
src = inspect.getsource(cls)
|
|
100
|
+
except (TypeError, OSError):
|
|
101
|
+
return propdocs
|
|
102
|
+
|
|
103
|
+
body = ast.parse(src).body[0]
|
|
104
|
+
|
|
105
|
+
for idx in range(len(body.body) - 1):
|
|
106
|
+
s = body.body[idx]
|
|
107
|
+
ss = body.body[idx+1]
|
|
108
|
+
if isinstance(s, ast.Assign) and isinstance(ss, ast.Expr) and isinstance(ss.value, ast.Constant):
|
|
109
|
+
for t in s.targets:
|
|
110
|
+
propdocs[t.id] = ss.value.value
|
|
111
|
+
|
|
112
|
+
return propdocs
|
|
113
|
+
|
|
114
|
+
def get_class_api_parameters_comments(cls):
|
|
115
|
+
return [{"name": n, "in": "query", "description": v} for n, v in _get_class_property_comments(cls).items()]
|
|
116
|
+
|
|
117
|
+
def get_class_api_parameters_inspect(cls):
|
|
118
|
+
return [{"name": n, "in": "query", "schema": {} if v is None else merge(make_type_schema(typeof(v)), make_value_schema(v))}
|
|
119
|
+
for n, v in inspect.getmembers(cls)
|
|
120
|
+
if (not n.startswith('__')
|
|
121
|
+
and not inspect.ismethod(v)
|
|
122
|
+
and not inspect.isfunction(v)
|
|
123
|
+
and not inspect.isdatadescriptor(v))]
|
|
124
|
+
|
|
125
|
+
def get_class_api_parameters_typing(cls):
|
|
126
|
+
return [{"name": k, "in": "query", "schema": make_type_schema(t)} for k, t in typing.get_type_hints(cls).items()]
|
|
127
|
+
|
|
128
|
+
def get_class_api(cls):
|
|
129
|
+
args = merge(get_class_api_parameters_typing(cls),
|
|
130
|
+
merge(get_class_api_parameters_inspect(cls),
|
|
131
|
+
get_class_api_parameters_comments(cls)))
|
|
132
|
+
return {
|
|
133
|
+
"operationId": _get_name(cls),
|
|
134
|
+
"description": inspect.getdoc(cls),
|
|
135
|
+
"parameters": args,
|
|
136
|
+
"responses": {"default":
|
|
137
|
+
{"description": _get_name(cls),
|
|
138
|
+
"content": {
|
|
139
|
+
"application/json": {"schema": make_type_schema(cls)}}}}}
|
|
140
|
+
|
|
141
|
+
def remove_hidden(api):
|
|
142
|
+
return [param for param in api
|
|
143
|
+
if not param.get("schema", {}).get("hide", False)]
|
|
144
|
+
|
|
145
|
+
def get_function_api_parameters_inspect(fn):
|
|
146
|
+
return remove_hidden(
|
|
147
|
+
[remove_empty({"name": k,
|
|
148
|
+
"in": "query",
|
|
149
|
+
"schema": merge(
|
|
150
|
+
make_type_schema(v.annotation, typeof(v.default)),
|
|
151
|
+
make_value_schema(v.default))})
|
|
152
|
+
for k, v in inspect.signature(fn).parameters.items()])
|
|
153
|
+
|
|
154
|
+
def get_function_api_parameters_comments(fn):
|
|
155
|
+
docs = inspect.getdoc(fn)
|
|
156
|
+
if docs is None: return []
|
|
157
|
+
docast = numpydoc.docscrape.NumpyDocString(docs)
|
|
158
|
+
|
|
159
|
+
return [{"name": p.name,
|
|
160
|
+
"in": "query",
|
|
161
|
+
"description": "\n".join(p.desc),
|
|
162
|
+
"schema": make_type_schema(p.type)}
|
|
163
|
+
for p in docast["Parameters"]]
|
|
164
|
+
|
|
165
|
+
def get_function_api(fn):
|
|
166
|
+
args = merge(get_function_api_parameters_inspect(fn),
|
|
167
|
+
get_function_api_parameters_comments(fn))
|
|
168
|
+
|
|
169
|
+
docs = inspect.getdoc(fn)
|
|
170
|
+
description = _get_name(fn)
|
|
171
|
+
if docs is not None:
|
|
172
|
+
docast = numpydoc.docscrape.NumpyDocString(docs)
|
|
173
|
+
description = "\n".join(docast["Summary"] + docast["Extended Summary"])
|
|
174
|
+
|
|
175
|
+
returntype = inspect.signature(fn).return_annotation
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
"operationId": _get_name(fn),
|
|
179
|
+
"description": description,
|
|
180
|
+
"parameters": args,
|
|
181
|
+
"responses": {"default":
|
|
182
|
+
{"description": _get_name(fn),
|
|
183
|
+
"content": {
|
|
184
|
+
"application/json": remove_empty({
|
|
185
|
+
"schema": make_type_schema(returntype)})}}}}
|
|
186
|
+
|
|
187
|
+
def get_api(obj):
|
|
188
|
+
"""Generate a swagger specification fragment for a single function
|
|
189
|
+
call or class instantiation."""
|
|
190
|
+
if type(obj) is type:
|
|
191
|
+
return get_class_api(obj)
|
|
192
|
+
elif inspect.isfunction(obj):
|
|
193
|
+
return get_function_api(obj)
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
def get_apis_dict(objs):
|
|
197
|
+
return {
|
|
198
|
+
"openapi": '3.0.3',
|
|
199
|
+
"info": {"title": "unknown",
|
|
200
|
+
"version": "1.0",
|
|
201
|
+
"description": "unknown"},
|
|
202
|
+
"paths": {
|
|
203
|
+
"/" + k: {"get": v}
|
|
204
|
+
for k, v in
|
|
205
|
+
[(k, get_api(v))
|
|
206
|
+
for k, v in objs.items()]
|
|
207
|
+
if v
|
|
208
|
+
}}
|
|
209
|
+
|
|
210
|
+
def get_apis_entrypoints(group):
|
|
211
|
+
entrypoints = importlib.metadata.entry_points()
|
|
212
|
+
if group not in entrypoints: return {}
|
|
213
|
+
entrypoints = entrypoints[group]
|
|
214
|
+
docs = get_apis_dict({entry.name: entry.load()
|
|
215
|
+
for entry in entrypoints})
|
|
216
|
+
docs["info"] = {"title": group,
|
|
217
|
+
"version": "1.0",
|
|
218
|
+
"description": group}
|
|
219
|
+
return docs
|
|
220
|
+
|
|
221
|
+
def get_apis_module(module):
|
|
222
|
+
if isinstance(module, str):
|
|
223
|
+
try:
|
|
224
|
+
module = importlib.import_module(module)
|
|
225
|
+
except:
|
|
226
|
+
return {}
|
|
227
|
+
docs = get_apis_dict({name: getattr(module, name)
|
|
228
|
+
for name in dir(module)
|
|
229
|
+
if not name.startswith("__")})
|
|
230
|
+
docs["info"] = {"title": module.__name__,
|
|
231
|
+
"version": "1.0",
|
|
232
|
+
"description": inspect.getdoc(module) or module.__name__}
|
|
233
|
+
return docs
|
|
234
|
+
|
|
235
|
+
def get_apis(objs):
|
|
236
|
+
"""Generates a swagger specification for module or entry point group."""
|
|
237
|
+
return merge(get_apis_module(objs), get_apis_entrypoints(objs))
|
|
238
|
+
|
|
239
|
+
def swagger_to_json_schema(api, multi = True):
|
|
240
|
+
"""Converts a swagger specification into a JSON schema for either
|
|
241
|
+
a single function call serialized as
|
|
242
|
+
|
|
243
|
+
{"function.name": {"argname1": "value1", ... "argnameN": "valueN"}}
|
|
244
|
+
|
|
245
|
+
or if multi is True (the default), a list of function calls each
|
|
246
|
+
serialized as above.
|
|
247
|
+
"""
|
|
248
|
+
if not api: return {}
|
|
249
|
+
schema = {
|
|
250
|
+
"description": api["info"]["description"],
|
|
251
|
+
"anyOf": [
|
|
252
|
+
{
|
|
253
|
+
"type": "object",
|
|
254
|
+
"title": step["operationId"],
|
|
255
|
+
"additionalProperties": False,
|
|
256
|
+
"properties": {
|
|
257
|
+
step["operationId"]: {
|
|
258
|
+
"type": "object",
|
|
259
|
+
"additionalProperties": False,
|
|
260
|
+
"properties": {
|
|
261
|
+
parameter["name"]: merge(
|
|
262
|
+
parameter.get("schema", {}),
|
|
263
|
+
remove_empty({"description": parameter.get("description"),
|
|
264
|
+
"default": parameter.get("default")
|
|
265
|
+
}))
|
|
266
|
+
for parameter in step["parameters"]
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for step in [path["get"] for path in api["paths"].values()]
|
|
272
|
+
]
|
|
273
|
+
}
|
|
274
|
+
if multi:
|
|
275
|
+
schema = {"type": "array", "items": schema}
|
|
276
|
+
return schema
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: swaggerspect
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Home-page: https://github.com/emerald-geomodelling/swaggerspect
|
|
5
|
+
Author: Egil Moeller
|
|
6
|
+
Author-email: em@emrld.no
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
|
|
10
|
+
Introspects python classes and functions and generates swagger style documentation objects.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
numpydoc
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
swaggerspect
|