polyapi-python 0.3.3.dev3__py3-none-any.whl → 0.3.3.dev9__py3-none-any.whl
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.
- polyapi/api.py +1 -0
- polyapi/cli.py +0 -2
- polyapi/config.py +5 -1
- polyapi/execute.py +6 -1
- polyapi/function_cli.py +2 -8
- polyapi/generate.py +12 -11
- polyapi/parser.py +9 -7
- polyapi/poly_schemas.py +50 -15
- polyapi/schema.py +17 -6
- polyapi/server.py +9 -5
- polyapi/utils.py +71 -17
- {polyapi_python-0.3.3.dev3.dist-info → polyapi_python-0.3.3.dev9.dist-info}/METADATA +12 -2
- polyapi_python-0.3.3.dev9.dist-info/RECORD +31 -0
- {polyapi_python-0.3.3.dev3.dist-info → polyapi_python-0.3.3.dev9.dist-info}/licenses/LICENSE +1 -1
- polyapi_python-0.3.3.dev3.dist-info/RECORD +0 -31
- {polyapi_python-0.3.3.dev3.dist-info → polyapi_python-0.3.3.dev9.dist-info}/WHEEL +0 -0
- {polyapi_python-0.3.3.dev3.dist-info → polyapi_python-0.3.3.dev9.dist-info}/top_level.txt +0 -0
polyapi/api.py
CHANGED
|
@@ -42,6 +42,7 @@ def render_api_function(
|
|
|
42
42
|
arg_names = [a["name"] for a in arguments]
|
|
43
43
|
args, args_def = parse_arguments(function_name, arguments)
|
|
44
44
|
return_type_name, return_type_def = get_type_and_def(return_type) # type: ignore
|
|
45
|
+
|
|
45
46
|
data = "{" + ", ".join([f"'{arg}': {rewrite_arg_name(arg)}" for arg in arg_names]) + "}"
|
|
46
47
|
|
|
47
48
|
api_response_type = f"{function_name}Response"
|
polyapi/cli.py
CHANGED
polyapi/config.py
CHANGED
|
@@ -55,6 +55,10 @@ def set_api_key_and_url(key: str, url: str):
|
|
|
55
55
|
config.set("polyapi", "poly_api_base_url", url)
|
|
56
56
|
with open(get_config_file_path(), "w") as f:
|
|
57
57
|
config.write(f)
|
|
58
|
+
global API_KEY
|
|
59
|
+
global API_URL
|
|
60
|
+
API_KEY = key
|
|
61
|
+
API_URL = url
|
|
58
62
|
|
|
59
63
|
|
|
60
64
|
def initialize_config(force=False):
|
|
@@ -81,7 +85,7 @@ def initialize_config(force=False):
|
|
|
81
85
|
sys.exit(1)
|
|
82
86
|
|
|
83
87
|
set_api_key_and_url(key, url)
|
|
84
|
-
print_green(
|
|
88
|
+
print_green("Poly setup complete.")
|
|
85
89
|
|
|
86
90
|
if not key or not url:
|
|
87
91
|
print_yellow("Poly API Key and Poly API Base URL are required.")
|
polyapi/execute.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
from typing import Dict
|
|
1
2
|
import requests
|
|
2
3
|
from requests import Response
|
|
3
4
|
from polyapi.config import get_api_key_and_url
|
|
@@ -7,10 +8,14 @@ from polyapi.exceptions import PolyApiException
|
|
|
7
8
|
def execute(function_type, function_id, data) -> Response:
|
|
8
9
|
""" execute a specific function id/type
|
|
9
10
|
"""
|
|
11
|
+
data_without_None = data
|
|
12
|
+
if isinstance(data, Dict):
|
|
13
|
+
data_without_None = {k: v for k, v in data.items() if v is not None}
|
|
14
|
+
|
|
10
15
|
api_key, api_url = get_api_key_and_url()
|
|
11
16
|
headers = {"Authorization": f"Bearer {api_key}"}
|
|
12
17
|
url = f"{api_url}/functions/{function_type}/{function_id}/execute"
|
|
13
|
-
resp = requests.post(url, json=
|
|
18
|
+
resp = requests.post(url, json=data_without_None, headers=headers)
|
|
14
19
|
# print(resp.status_code)
|
|
15
20
|
# print(resp.headers["content-type"])
|
|
16
21
|
if resp.status_code < 200 or resp.status_code >= 300:
|
polyapi/function_cli.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
from typing import Any, List, Optional
|
|
3
3
|
import requests
|
|
4
|
-
from polyapi.generate import
|
|
4
|
+
from polyapi.generate import generate as generate_library
|
|
5
5
|
from polyapi.config import get_api_key_and_url
|
|
6
6
|
from polyapi.utils import get_auth_headers, print_green, print_red, print_yellow
|
|
7
7
|
from polyapi.parser import parse_function_code, get_jsonschema_type
|
|
@@ -87,13 +87,7 @@ def function_add_or_update(
|
|
|
87
87
|
function_id = resp.json()["id"]
|
|
88
88
|
print(f"Function ID: {function_id}")
|
|
89
89
|
if generate:
|
|
90
|
-
|
|
91
|
-
# TODO do something more efficient here rather than regetting ALL the specs again
|
|
92
|
-
specs = get_specs()
|
|
93
|
-
cache_specs(specs)
|
|
94
|
-
functions = parse_function_specs(specs)
|
|
95
|
-
generate_functions(functions)
|
|
96
|
-
print_green("DONE")
|
|
90
|
+
generate_library()
|
|
97
91
|
else:
|
|
98
92
|
print("Error adding function.")
|
|
99
93
|
print(resp.status_code)
|
polyapi/generate.py
CHANGED
|
@@ -2,18 +2,17 @@ import json
|
|
|
2
2
|
import requests
|
|
3
3
|
import os
|
|
4
4
|
import shutil
|
|
5
|
-
from typing import List, cast
|
|
5
|
+
from typing import List, Tuple, cast
|
|
6
6
|
|
|
7
|
-
from
|
|
8
|
-
from
|
|
9
|
-
from
|
|
10
|
-
from
|
|
11
|
-
from polyapi.webhook import render_webhook_handle
|
|
7
|
+
from .auth import render_auth_function
|
|
8
|
+
from .client import render_client_function
|
|
9
|
+
from .poly_schemas import generate_schemas
|
|
10
|
+
from .webhook import render_webhook_handle
|
|
12
11
|
|
|
13
12
|
from .typedefs import PropertySpecification, SchemaSpecDto, SpecificationDto, VariableSpecDto
|
|
14
13
|
from .api import render_api_function
|
|
15
14
|
from .server import render_server_function
|
|
16
|
-
from .utils import add_import_to_init, get_auth_headers, init_the_init, to_func_namespace
|
|
15
|
+
from .utils import add_import_to_init, get_auth_headers, init_the_init, print_green, to_func_namespace
|
|
17
16
|
from .variables import generate_variables
|
|
18
17
|
from .config import get_api_key_and_url
|
|
19
18
|
|
|
@@ -175,13 +174,13 @@ def remove_old_library():
|
|
|
175
174
|
|
|
176
175
|
|
|
177
176
|
def generate() -> None:
|
|
178
|
-
|
|
177
|
+
print("Generating Poly Python SDK...", end="", flush=True)
|
|
179
178
|
remove_old_library()
|
|
180
179
|
|
|
181
|
-
limit_ids: List[str] = [] # useful for narrowing down generation to a single function to debug
|
|
182
|
-
|
|
183
180
|
specs = get_specs()
|
|
184
181
|
cache_specs(specs)
|
|
182
|
+
|
|
183
|
+
limit_ids: List[str] = [] # useful for narrowing down generation to a single function to debug
|
|
185
184
|
functions = parse_function_specs(specs, limit_ids=limit_ids)
|
|
186
185
|
|
|
187
186
|
schemas = get_schemas()
|
|
@@ -208,6 +207,8 @@ def generate() -> None:
|
|
|
208
207
|
file_path = os.path.join(os.getcwd(), ".polyapi-python")
|
|
209
208
|
open(file_path, "w").close()
|
|
210
209
|
|
|
210
|
+
print_green("DONE")
|
|
211
|
+
|
|
211
212
|
|
|
212
213
|
def clear() -> None:
|
|
213
214
|
base = os.path.dirname(os.path.abspath(__file__))
|
|
@@ -221,7 +222,7 @@ def clear() -> None:
|
|
|
221
222
|
print("Cleared!")
|
|
222
223
|
|
|
223
224
|
|
|
224
|
-
def render_spec(spec: SpecificationDto):
|
|
225
|
+
def render_spec(spec: SpecificationDto) -> Tuple[str, str]:
|
|
225
226
|
function_type = spec["type"]
|
|
226
227
|
function_description = spec["description"]
|
|
227
228
|
function_name = spec["name"]
|
polyapi/parser.py
CHANGED
|
@@ -5,7 +5,7 @@ import sys
|
|
|
5
5
|
import re
|
|
6
6
|
from typing import Dict, List, Mapping, Optional, Tuple, Any
|
|
7
7
|
from typing import _TypedDictMeta as BaseTypedDict # type: ignore
|
|
8
|
-
from typing_extensions import _TypedDictMeta
|
|
8
|
+
from typing_extensions import _TypedDictMeta, cast # type: ignore
|
|
9
9
|
from stdlib_list import stdlib_list
|
|
10
10
|
from pydantic import TypeAdapter
|
|
11
11
|
from importlib.metadata import packages_distributions
|
|
@@ -158,6 +158,7 @@ def _parse_google_docstring(docstring: str) -> Dict[str, Any]:
|
|
|
158
158
|
|
|
159
159
|
return parsed
|
|
160
160
|
|
|
161
|
+
|
|
161
162
|
def _get_schemas(code: str) -> List[Dict]:
|
|
162
163
|
schemas = []
|
|
163
164
|
user_code = types.SimpleNamespace()
|
|
@@ -245,7 +246,7 @@ def _get_type_schema(json_type: str, python_type: str, schemas: List[Dict]):
|
|
|
245
246
|
return schema
|
|
246
247
|
|
|
247
248
|
|
|
248
|
-
def _get_type(expr: ast.expr | None, schemas: List[Dict]) -> Tuple[
|
|
249
|
+
def _get_type(expr: ast.expr | None, schemas: List[Dict]) -> Tuple[Any, Any, Any]:
|
|
249
250
|
if not expr:
|
|
250
251
|
return "any", "Any", None
|
|
251
252
|
python_type = get_python_type_from_ast(expr)
|
|
@@ -317,7 +318,7 @@ def _parse_value(value):
|
|
|
317
318
|
return None
|
|
318
319
|
|
|
319
320
|
|
|
320
|
-
def parse_function_code(code: str, name: Optional[str] = "", context: Optional[str] = ""):
|
|
321
|
+
def parse_function_code(code: str, name: Optional[str] = "", context: Optional[str] = ""): # noqa: C901
|
|
321
322
|
schemas = _get_schemas(code)
|
|
322
323
|
|
|
323
324
|
# the pip name and the import name might be different
|
|
@@ -325,9 +326,9 @@ def parse_function_code(code: str, name: Optional[str] = "", context: Optional[s
|
|
|
325
326
|
# see https://stackoverflow.com/a/75144378
|
|
326
327
|
pip_name_lookup = packages_distributions()
|
|
327
328
|
|
|
328
|
-
deployable: DeployableRecord = {
|
|
329
|
-
"context": context,
|
|
330
|
-
"name": name,
|
|
329
|
+
deployable: DeployableRecord = { # type: ignore
|
|
330
|
+
"context": context, # type: ignore
|
|
331
|
+
"name": name, # type: ignore
|
|
331
332
|
"description": "",
|
|
332
333
|
"config": {},
|
|
333
334
|
"gitRevision": "",
|
|
@@ -381,7 +382,7 @@ def parse_function_code(code: str, name: Optional[str] = "", context: Optional[s
|
|
|
381
382
|
if node.annotation.id == "PolyServerFunction":
|
|
382
383
|
deployable["type"] = "server-function"
|
|
383
384
|
elif node.annotation.id == "PolyClientFunction":
|
|
384
|
-
deployable["type"] = "
|
|
385
|
+
deployable["type"] = "client-function"
|
|
385
386
|
else:
|
|
386
387
|
print_red("ERROR")
|
|
387
388
|
print(f"Unsupported polyConfig type '${node.annotation.id}'")
|
|
@@ -404,6 +405,7 @@ def parse_function_code(code: str, name: Optional[str] = "", context: Optional[s
|
|
|
404
405
|
if type(docstring) is None or (not docstring and '"""' not in self._lines[start_lineno] and "'''" not in self._lines[start_lineno]):
|
|
405
406
|
return None
|
|
406
407
|
|
|
408
|
+
docstring = cast(str, docstring)
|
|
407
409
|
|
|
408
410
|
# Support both types of triple quotation marks
|
|
409
411
|
pattern = '"""'
|
polyapi/poly_schemas.py
CHANGED
|
@@ -2,12 +2,14 @@ import os
|
|
|
2
2
|
from typing import Any, Dict, List, Tuple
|
|
3
3
|
|
|
4
4
|
from polyapi.schema import wrapped_generate_schema_types
|
|
5
|
-
from polyapi.utils import add_import_to_init, init_the_init
|
|
5
|
+
from polyapi.utils import add_import_to_init, init_the_init, to_func_namespace
|
|
6
6
|
|
|
7
7
|
from .typedefs import SchemaSpecDto
|
|
8
8
|
|
|
9
9
|
SCHEMA_CODE_IMPORTS = """from typing_extensions import TypedDict, NotRequired
|
|
10
10
|
|
|
11
|
+
__all__ = []
|
|
12
|
+
|
|
11
13
|
|
|
12
14
|
"""
|
|
13
15
|
|
|
@@ -23,23 +25,56 @@ def generate_schemas(specs: List[SchemaSpecDto]):
|
|
|
23
25
|
create_schema(spec)
|
|
24
26
|
|
|
25
27
|
|
|
26
|
-
def
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
def add_schema_file(
|
|
29
|
+
full_path: str,
|
|
30
|
+
schema_name: str,
|
|
31
|
+
spec: SchemaSpecDto,
|
|
32
|
+
):
|
|
33
|
+
# first lets add the import to the __init__
|
|
34
|
+
init_the_init(full_path, SCHEMA_CODE_IMPORTS)
|
|
35
|
+
|
|
36
|
+
if not spec["definition"].get("title"):
|
|
37
|
+
# very empty schemas like mews.Unit are possible
|
|
38
|
+
# add a title here to be sure they render
|
|
39
|
+
spec["definition"]["title"] = schema_name
|
|
40
|
+
|
|
41
|
+
schema_defs = render_poly_schema(spec)
|
|
42
|
+
|
|
43
|
+
if schema_defs:
|
|
44
|
+
# add function to init
|
|
45
|
+
init_path = os.path.join(full_path, "__init__.py")
|
|
46
|
+
with open(init_path, "a") as f:
|
|
47
|
+
f.write(f"\n\nfrom ._{to_func_namespace(schema_name)} import {schema_name}\n__all__.append('{schema_name}')\n")
|
|
48
|
+
|
|
49
|
+
# add type_defs to underscore file
|
|
50
|
+
file_path = os.path.join(full_path, f"_{to_func_namespace(schema_name)}.py")
|
|
51
|
+
with open(file_path, "w") as f:
|
|
52
|
+
f.write(schema_defs)
|
|
30
53
|
|
|
31
|
-
# build up the full_path by adding all the folders
|
|
32
|
-
full_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
|
|
33
54
|
|
|
55
|
+
def create_schema(
|
|
56
|
+
spec: SchemaSpecDto
|
|
57
|
+
) -> None:
|
|
58
|
+
full_path = os.path.dirname(os.path.abspath(__file__))
|
|
59
|
+
folders = f"schemas.{spec['context']}.{spec['name']}".split(".")
|
|
34
60
|
for idx, folder in enumerate(folders):
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
61
|
+
if idx + 1 == len(folders):
|
|
62
|
+
# special handling for final level
|
|
63
|
+
add_schema_file(
|
|
64
|
+
full_path,
|
|
65
|
+
folder,
|
|
66
|
+
spec,
|
|
67
|
+
)
|
|
68
|
+
else:
|
|
69
|
+
full_path = os.path.join(full_path, folder)
|
|
70
|
+
if not os.path.exists(full_path):
|
|
71
|
+
os.makedirs(full_path)
|
|
72
|
+
|
|
73
|
+
# append to __init__.py file if nested folders
|
|
74
|
+
next = folders[idx + 1] if idx + 2 < len(folders) else ""
|
|
75
|
+
if next:
|
|
76
|
+
init_the_init(full_path, SCHEMA_CODE_IMPORTS)
|
|
77
|
+
add_import_to_init(full_path, next)
|
|
43
78
|
|
|
44
79
|
|
|
45
80
|
def add_schema_to_init(full_path: str, spec: SchemaSpecDto):
|
polyapi/schema.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
""" NOTE: this file represents the schema parsing logic for jsonschema_gentypes
|
|
2
2
|
"""
|
|
3
|
-
import random
|
|
4
|
-
import string
|
|
5
3
|
import logging
|
|
6
4
|
import contextlib
|
|
5
|
+
import re
|
|
7
6
|
from typing import Dict
|
|
8
7
|
from jsonschema_gentypes.cli import process_config
|
|
9
8
|
from jsonschema_gentypes import configuration
|
|
@@ -48,10 +47,8 @@ def wrapped_generate_schema_types(type_spec: dict, root, fallback_type):
|
|
|
48
47
|
# lets name the root after the reference for some level of visibility
|
|
49
48
|
root += pascalCase(type_spec["x-poly-ref"]["path"].replace(".", " "))
|
|
50
49
|
else:
|
|
51
|
-
#
|
|
52
|
-
root
|
|
53
|
-
root += random.choice(string.ascii_letters).upper()
|
|
54
|
-
root += random.choice(string.ascii_letters).upper()
|
|
50
|
+
# if we have no root, just add "My"
|
|
51
|
+
root = "My" + root
|
|
55
52
|
|
|
56
53
|
root = clean_title(root)
|
|
57
54
|
|
|
@@ -99,9 +96,23 @@ def generate_schema_types(input_data: Dict, root=None):
|
|
|
99
96
|
with open(tmp_output) as f:
|
|
100
97
|
output = f.read()
|
|
101
98
|
|
|
99
|
+
output = clean_malformed_examples(output)
|
|
100
|
+
|
|
102
101
|
return output
|
|
103
102
|
|
|
104
103
|
|
|
104
|
+
# Regex to match everything between "# example: {\n" and "^}$"
|
|
105
|
+
MALFORMED_EXAMPLES_PATTERN = re.compile(r"# example: \{\n.*?^\}$", flags=re.DOTALL | re.MULTILINE)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def clean_malformed_examples(example: str) -> str:
|
|
109
|
+
""" there is a bug in the `jsonschmea_gentypes` library where if an example from a jsonchema is an object,
|
|
110
|
+
it will break the code because the object won't be properly commented out
|
|
111
|
+
"""
|
|
112
|
+
cleaned_example = MALFORMED_EXAMPLES_PATTERN.sub("", example)
|
|
113
|
+
return cleaned_example
|
|
114
|
+
|
|
115
|
+
|
|
105
116
|
def clean_title(title: str) -> str:
|
|
106
117
|
""" used by library generation, sometimes functions can be added with spaces in the title
|
|
107
118
|
or other nonsense. fix them!
|
polyapi/server.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
from typing import Any, Dict, List, Tuple
|
|
1
|
+
from typing import Any, Dict, List, Tuple, cast
|
|
2
2
|
|
|
3
|
-
from polyapi.typedefs import PropertySpecification
|
|
4
|
-
from polyapi.utils import add_type_import_path, parse_arguments, get_type_and_def, rewrite_arg_name
|
|
3
|
+
from polyapi.typedefs import PropertySpecification, PropertyType
|
|
4
|
+
from polyapi.utils import add_type_import_path, parse_arguments, get_type_and_def, return_type_already_defined_in_args, rewrite_arg_name
|
|
5
5
|
|
|
6
6
|
SERVER_DEFS_TEMPLATE = """
|
|
7
7
|
from typing import List, Dict, Any, TypedDict, Callable
|
|
@@ -21,7 +21,7 @@ def {function_name}(
|
|
|
21
21
|
try:
|
|
22
22
|
return {return_action}
|
|
23
23
|
except:
|
|
24
|
-
return resp.text
|
|
24
|
+
return resp.text # type: ignore # fallback for debugging
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
"""
|
|
@@ -37,7 +37,11 @@ def render_server_function(
|
|
|
37
37
|
) -> Tuple[str, str]:
|
|
38
38
|
arg_names = [a["name"] for a in arguments]
|
|
39
39
|
args, args_def = parse_arguments(function_name, arguments)
|
|
40
|
-
return_type_name, return_type_def = get_type_and_def(return_type)
|
|
40
|
+
return_type_name, return_type_def = get_type_and_def(cast(PropertyType, return_type), "ReturnType")
|
|
41
|
+
|
|
42
|
+
if return_type_def and return_type_already_defined_in_args(return_type_name, args_def):
|
|
43
|
+
return_type_def = ""
|
|
44
|
+
|
|
41
45
|
data = "{" + ", ".join([f"'{arg}': {rewrite_arg_name(arg)}" for arg in arg_names]) + "}"
|
|
42
46
|
func_type_defs = SERVER_DEFS_TEMPLATE.format(
|
|
43
47
|
args_def=args_def,
|
polyapi/utils.py
CHANGED
|
@@ -6,7 +6,11 @@ from typing import Tuple, List
|
|
|
6
6
|
from colorama import Fore, Style
|
|
7
7
|
from polyapi.constants import BASIC_PYTHON_TYPES
|
|
8
8
|
from polyapi.typedefs import PropertySpecification, PropertyType
|
|
9
|
-
from polyapi.schema import
|
|
9
|
+
from polyapi.schema import (
|
|
10
|
+
wrapped_generate_schema_types,
|
|
11
|
+
clean_title,
|
|
12
|
+
map_primitive_types,
|
|
13
|
+
)
|
|
10
14
|
|
|
11
15
|
|
|
12
16
|
# this string should be in every __init__ file.
|
|
@@ -42,7 +46,7 @@ def camelCase(s: str) -> str:
|
|
|
42
46
|
s = s.strip()
|
|
43
47
|
if " " in s or "-" in s:
|
|
44
48
|
s = re.sub(r"(_|-)+", " ", s).title().replace(" ", "")
|
|
45
|
-
return
|
|
49
|
+
return "".join([s[0].lower(), s[1:]])
|
|
46
50
|
else:
|
|
47
51
|
# s is already in camelcase as best as we can tell, just move on!
|
|
48
52
|
return s
|
|
@@ -65,8 +69,7 @@ def print_red(s: str):
|
|
|
65
69
|
|
|
66
70
|
|
|
67
71
|
def add_type_import_path(function_name: str, arg: str) -> str:
|
|
68
|
-
"""
|
|
69
|
-
"""
|
|
72
|
+
"""if not basic type, coerce to camelCase and add the import path"""
|
|
70
73
|
# for now, just treat Callables as basic types
|
|
71
74
|
if arg.startswith("Callable"):
|
|
72
75
|
return arg
|
|
@@ -83,12 +86,16 @@ def add_type_import_path(function_name: str, arg: str) -> str:
|
|
|
83
86
|
sub = sub.replace('"', "")
|
|
84
87
|
return f'List["{to_func_namespace(function_name)}.{camelCase(sub)}"]'
|
|
85
88
|
else:
|
|
86
|
-
return f
|
|
89
|
+
return f"List[{to_func_namespace(function_name)}.{camelCase(sub)}]"
|
|
87
90
|
|
|
88
|
-
return f
|
|
91
|
+
return f"{to_func_namespace(function_name)}.{camelCase(arg)}"
|
|
89
92
|
|
|
90
93
|
|
|
91
|
-
def get_type_and_def(
|
|
94
|
+
def get_type_and_def(
|
|
95
|
+
type_spec: PropertyType, title_fallback: str = ""
|
|
96
|
+
) -> Tuple[str, str]:
|
|
97
|
+
""" returns type and type definition for a given PropertyType
|
|
98
|
+
"""
|
|
92
99
|
if type_spec["kind"] == "plain":
|
|
93
100
|
value = type_spec["value"]
|
|
94
101
|
if value.endswith("[]"):
|
|
@@ -115,15 +122,19 @@ def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
|
|
|
115
122
|
elif type_spec["kind"] == "object":
|
|
116
123
|
if type_spec.get("schema"):
|
|
117
124
|
schema = type_spec["schema"]
|
|
118
|
-
title = schema.get("title", schema.get("name",
|
|
119
|
-
if title:
|
|
125
|
+
title = schema.get("title", schema.get("name", title_fallback))
|
|
126
|
+
if title and schema.get("type") == "array":
|
|
127
|
+
# TODO fix me
|
|
128
|
+
# we don't use ReturnType as name for the list type here, we use _ReturnTypeItem
|
|
129
|
+
return "List", ""
|
|
130
|
+
elif title:
|
|
120
131
|
assert isinstance(title, str)
|
|
121
132
|
return wrapped_generate_schema_types(schema, title, "Dict") # type: ignore
|
|
122
|
-
elif schema.get("allOf") and len(schema[
|
|
133
|
+
elif schema.get("allOf") and len(schema["allOf"]):
|
|
123
134
|
# we are in a case of a single allOf, lets strip off the allOf and move on!
|
|
124
135
|
# our library doesn't handle allOf well yet
|
|
125
|
-
allOf = schema[
|
|
126
|
-
title = allOf.get("title", allOf.get("name",
|
|
136
|
+
allOf = schema["allOf"][0]
|
|
137
|
+
title = allOf.get("title", allOf.get("name", title_fallback))
|
|
127
138
|
return wrapped_generate_schema_types(allOf, title, "Dict")
|
|
128
139
|
elif schema.get("items"):
|
|
129
140
|
# fallback to schema $ref name if no explicit title
|
|
@@ -131,7 +142,7 @@ def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
|
|
|
131
142
|
title = items.get("title") # type: ignore
|
|
132
143
|
if not title:
|
|
133
144
|
# title is actually a reference to another schema
|
|
134
|
-
title = items.get("$ref",
|
|
145
|
+
title = items.get("$ref", title_fallback) # type: ignore
|
|
135
146
|
|
|
136
147
|
title = title.rsplit("/", 1)[-1]
|
|
137
148
|
if not title:
|
|
@@ -153,12 +164,18 @@ def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
|
|
|
153
164
|
return_type = "Any"
|
|
154
165
|
|
|
155
166
|
for argument in type_spec["spec"]["arguments"]:
|
|
167
|
+
# do NOT add this fallback here
|
|
168
|
+
# callable arguments don't understand the imports yet
|
|
169
|
+
# if it's not a basic type here, we'll just do Any
|
|
170
|
+
# _maybe_add_fallback_schema_name(argument)
|
|
156
171
|
arg_type, arg_def = get_type_and_def(argument["type"])
|
|
157
172
|
arg_types.append(arg_type)
|
|
158
173
|
if arg_def:
|
|
159
174
|
arg_defs.append(arg_def)
|
|
160
175
|
|
|
161
|
-
final_arg_type = "Callable[[{}], {}]".format(
|
|
176
|
+
final_arg_type = "Callable[[{}], {}]".format(
|
|
177
|
+
", ".join(arg_types), return_type
|
|
178
|
+
)
|
|
162
179
|
return final_arg_type, "\n".join(arg_defs)
|
|
163
180
|
else:
|
|
164
181
|
return "Callable", ""
|
|
@@ -168,15 +185,30 @@ def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
|
|
|
168
185
|
return "Any", ""
|
|
169
186
|
|
|
170
187
|
|
|
171
|
-
def
|
|
188
|
+
def _maybe_add_fallback_schema_name(a: PropertySpecification):
|
|
189
|
+
if a["type"]["kind"] == "object" and a["type"].get("schema"):
|
|
190
|
+
schema = a["type"].get("schema", {})
|
|
191
|
+
if not schema.get("title") and not schema.get("name") and a["name"]:
|
|
192
|
+
schema["title"] = a["name"].title()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def parse_arguments(
|
|
196
|
+
function_name: str, arguments: List[PropertySpecification]
|
|
197
|
+
) -> Tuple[str, str]:
|
|
172
198
|
args_def = []
|
|
173
199
|
arg_string = ""
|
|
174
200
|
for idx, a in enumerate(arguments):
|
|
201
|
+
_maybe_add_fallback_schema_name(a)
|
|
175
202
|
arg_type, arg_def = get_type_and_def(a["type"])
|
|
176
203
|
if arg_def:
|
|
177
204
|
args_def.append(arg_def)
|
|
178
205
|
a["name"] = rewrite_arg_name(a["name"])
|
|
179
|
-
arg_string +=
|
|
206
|
+
arg_string += (
|
|
207
|
+
f" {a['name']}: {add_type_import_path(function_name, arg_type)}"
|
|
208
|
+
)
|
|
209
|
+
if not a["required"]:
|
|
210
|
+
arg_string += " = None"
|
|
211
|
+
|
|
180
212
|
description = a.get("description", "")
|
|
181
213
|
description = description.replace("\n", " ")
|
|
182
214
|
if description:
|
|
@@ -202,7 +234,7 @@ RESERVED_WORDS = {"List", "Dict", "Any", "Optional", "Callable"} | set(keyword.k
|
|
|
202
234
|
|
|
203
235
|
|
|
204
236
|
def to_func_namespace(s: str) -> str:
|
|
205
|
-
"""
|
|
237
|
+
"""convert a function name to some function namespace
|
|
206
238
|
by default it is
|
|
207
239
|
"""
|
|
208
240
|
rv = s[0].upper() + s[1:]
|
|
@@ -221,6 +253,10 @@ def rewrite_arg_name(s: str):
|
|
|
221
253
|
return rewrite_reserved(camelCase(s))
|
|
222
254
|
|
|
223
255
|
|
|
256
|
+
# def get_return_type_name(function_name: str) -> str:
|
|
257
|
+
# return function_name[0].upper() + function_name[1:] + "ReturnType"
|
|
258
|
+
|
|
259
|
+
|
|
224
260
|
valid_subdomains = ["na[1-2]", "eu[1-2]", "dev"]
|
|
225
261
|
|
|
226
262
|
|
|
@@ -238,3 +274,21 @@ def is_valid_uuid(uuid_string, version=4):
|
|
|
238
274
|
return False
|
|
239
275
|
|
|
240
276
|
return str(uuid_obj) == uuid_string
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def return_type_already_defined_in_args(return_type_name: str, args_def: str) -> bool:
|
|
280
|
+
"""
|
|
281
|
+
Checks if the return_type_name preceded optionally by 'class ' and followed by ' =' exists in args_def.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
return_type_name (str): The name of the return type to check.
|
|
285
|
+
args_def (str): The string containing argument definitions.
|
|
286
|
+
|
|
287
|
+
Returns:
|
|
288
|
+
bool: True if the pattern exists, False otherwise.
|
|
289
|
+
"""
|
|
290
|
+
basic_pattern = rf"^{re.escape(return_type_name)}\s="
|
|
291
|
+
basic_match = bool(re.search(basic_pattern, args_def, re.MULTILINE))
|
|
292
|
+
class_pattern = rf"^class {re.escape(return_type_name)}\(TypedDict"
|
|
293
|
+
class_match = bool(re.search(class_pattern, args_def, re.MULTILINE))
|
|
294
|
+
return basic_match or class_match
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: polyapi-python
|
|
3
|
-
Version: 0.3.3.
|
|
3
|
+
Version: 0.3.3.dev9
|
|
4
4
|
Summary: The Python Client for PolyAPI, the IPaaS by Developers for Developers
|
|
5
5
|
Author-email: Dan Fellin <dan@polyapi.io>
|
|
6
6
|
License: MIT License
|
|
7
7
|
|
|
8
|
-
Copyright (c)
|
|
8
|
+
Copyright (c) 2025 PolyAPI Inc.
|
|
9
9
|
|
|
10
10
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
11
|
of this software and associated documentation files (the "Software"), to deal
|
|
@@ -193,6 +193,16 @@ When hacking on this library, please enable flake8 and add this line to your fla
|
|
|
193
193
|
--config=.flake8
|
|
194
194
|
```
|
|
195
195
|
|
|
196
|
+
## Mypy Type Improvements
|
|
197
|
+
|
|
198
|
+
This script is handy for checking for any mypy types:
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
./check_mypy.sh
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Please ignore \[name-defined\] errors for now. This is a known bug we are working to fix!
|
|
205
|
+
|
|
196
206
|
## Support
|
|
197
207
|
|
|
198
208
|
If you run into any issues or want help getting started with this project, please contact support@polyapi.io
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
polyapi/__init__.py,sha256=a1Poy1kaTncYnUg6nWRcTjVm-R1CUQk12UX7VYQ9d5k,616
|
|
2
|
+
polyapi/__main__.py,sha256=V4zhAh_YGxno5f_KSrlkELxcuDh9bR3WSd0n-2r-qQQ,93
|
|
3
|
+
polyapi/api.py,sha256=f1037HFJF7DtQSSypM4PE5AmmxWxjd0JiW6ARZqrgac,1879
|
|
4
|
+
polyapi/auth.py,sha256=zrIGatjba5GwUTNjKj1GHQWTEDP9B-HrSzCKbLFoqvc,5336
|
|
5
|
+
polyapi/cli.py,sha256=AKsWVHZPKGnypOdnzIpoZOsTuwcAuDGQajXhLe9OQKI,8239
|
|
6
|
+
polyapi/client.py,sha256=CoFDYvyKsqL4wPQbUDIr0Qb8Q5eD92xN4OEEcJEVuGQ,1296
|
|
7
|
+
polyapi/config.py,sha256=Vgc_q9FYXWGCOTr13EbpD0AwHks0Nflimy1NtZxgynA,3088
|
|
8
|
+
polyapi/constants.py,sha256=sc-FnS0SngBLvSu1ZWMs0UCf9EYD1u1Yhfr-sZXGLns,607
|
|
9
|
+
polyapi/deployables.py,sha256=WVcNNB6W5ZW_-ukf_kK3moRcnwIkC-O4te6vLepjcco,11936
|
|
10
|
+
polyapi/error_handler.py,sha256=I_e0iz6VM23FLVQWJljxs2NGcl_OODbi43OcbnqBlp8,2398
|
|
11
|
+
polyapi/exceptions.py,sha256=Zh7i7eCUhDuXEdUYjatkLFTeZkrx1BJ1P5ePgbJ9eIY,89
|
|
12
|
+
polyapi/execute.py,sha256=T9lXtiOz-JZTJgBKvJptA5_mz31qvYa6-O4NzM52mq4,2118
|
|
13
|
+
polyapi/function_cli.py,sha256=htgmcx_dPmw4_5NKRgIivcwS7D8bkOsxCTOrJhzV3pU,3989
|
|
14
|
+
polyapi/generate.py,sha256=IIbU4Kc8Ut-N3cPI1qzgV3M4r_GHi39dgU0ngpUY86Q,10473
|
|
15
|
+
polyapi/parser.py,sha256=mdoh4pNq8pyiHE0-i6Coqj8frEXfBLRk6itpAXMrrgI,20373
|
|
16
|
+
polyapi/poly_schemas.py,sha256=KFVmpB047pWQaTkiCJ3A9sUTNplTS8JETon1Sm2lnQs,2969
|
|
17
|
+
polyapi/prepare.py,sha256=Q8CWV4kmZ2dbXYVsud34AgJkj5ymcQ_IcYhLuikc9yk,6659
|
|
18
|
+
polyapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
|
+
polyapi/rendered_spec.py,sha256=uaNzBhP4cX7iGfKwzZv0dxMagWzsGeDr0cQYx_AyIhQ,2153
|
|
20
|
+
polyapi/schema.py,sha256=ZSzeUjpqigLvE4tFKB7y4AaZG-W5N5Z9wMH-F-vjMBU,4616
|
|
21
|
+
polyapi/server.py,sha256=YXWxhYBx-hluwDQ8Jvfpy2s8ogz0GsNTMcZVNcP5ca8,2147
|
|
22
|
+
polyapi/sync.py,sha256=PGdC0feBBjEVrF3d9EluW_OAxbWuzSrfh84czma8kWg,6476
|
|
23
|
+
polyapi/typedefs.py,sha256=KniVl7vwcDOhgAJmHSgTJKkP0rKWvSLIPOGsWuf9jRU,2239
|
|
24
|
+
polyapi/utils.py,sha256=K6QMKEf2fgmh3AswyNBADfv53sIOSAbXmGx2MaW5vy8,10261
|
|
25
|
+
polyapi/variables.py,sha256=d36-trnfTL_8m2NkorMiImb4O3UrJbiFV38CHxV5i0A,4200
|
|
26
|
+
polyapi/webhook.py,sha256=LWv28c2MLz_OKBI_Nn7WR4C-gs1SWgbdXsoxIIf-9UI,4886
|
|
27
|
+
polyapi_python-0.3.3.dev9.dist-info/licenses/LICENSE,sha256=6b_I7aPVp8JXhqQwdw7_B84Ca0S4JGjHj0sr_1VOdB4,1068
|
|
28
|
+
polyapi_python-0.3.3.dev9.dist-info/METADATA,sha256=fd2KtyjZKHie7x1Ua2p-QshQIE4Rc8gb5CMczxqGqgg,5782
|
|
29
|
+
polyapi_python-0.3.3.dev9.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
30
|
+
polyapi_python-0.3.3.dev9.dist-info/top_level.txt,sha256=CEFllOnzowci_50RYJac-M54KD2IdAptFsayVVF_f04,8
|
|
31
|
+
polyapi_python-0.3.3.dev9.dist-info/RECORD,,
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
polyapi/__init__.py,sha256=a1Poy1kaTncYnUg6nWRcTjVm-R1CUQk12UX7VYQ9d5k,616
|
|
2
|
-
polyapi/__main__.py,sha256=V4zhAh_YGxno5f_KSrlkELxcuDh9bR3WSd0n-2r-qQQ,93
|
|
3
|
-
polyapi/api.py,sha256=8gXypLOgySjg3fWD_K192idYWPNLBU09c9N35b8irxA,1878
|
|
4
|
-
polyapi/auth.py,sha256=zrIGatjba5GwUTNjKj1GHQWTEDP9B-HrSzCKbLFoqvc,5336
|
|
5
|
-
polyapi/cli.py,sha256=bTTEj8n0w-CrkkXuOqxC60iCIWKIGWyPiIuFZbspG6Q,8322
|
|
6
|
-
polyapi/client.py,sha256=CoFDYvyKsqL4wPQbUDIr0Qb8Q5eD92xN4OEEcJEVuGQ,1296
|
|
7
|
-
polyapi/config.py,sha256=uvEvOfWYZTLmBmZX-5jJxCzWPpwzVmEOIiQIdi98P4Y,3015
|
|
8
|
-
polyapi/constants.py,sha256=sc-FnS0SngBLvSu1ZWMs0UCf9EYD1u1Yhfr-sZXGLns,607
|
|
9
|
-
polyapi/deployables.py,sha256=WVcNNB6W5ZW_-ukf_kK3moRcnwIkC-O4te6vLepjcco,11936
|
|
10
|
-
polyapi/error_handler.py,sha256=I_e0iz6VM23FLVQWJljxs2NGcl_OODbi43OcbnqBlp8,2398
|
|
11
|
-
polyapi/exceptions.py,sha256=Zh7i7eCUhDuXEdUYjatkLFTeZkrx1BJ1P5ePgbJ9eIY,89
|
|
12
|
-
polyapi/execute.py,sha256=kXnvlNQ7nz9cRlV2_5gXH09UCmyiDP5zi3wiAw0uDuk,1943
|
|
13
|
-
polyapi/function_cli.py,sha256=IYihaDrTcPQDbuXmNn_5iEjSjRbOe--kRqVZ-svJ5zY,4340
|
|
14
|
-
polyapi/generate.py,sha256=MX8uDRTmZJMQCiHsyMreDEkx7Ip7b-Lnewgyi9My7S4,10402
|
|
15
|
-
polyapi/parser.py,sha256=Dqkg7cy9yae9HP4WcPtNzyZxrUrtDsGshFYW-vPvTzE,20263
|
|
16
|
-
polyapi/poly_schemas.py,sha256=malK9s0DB_am0tMOZ0bwyjXZmABAQ1WnZpP-IJhpb2g,1845
|
|
17
|
-
polyapi/prepare.py,sha256=Q8CWV4kmZ2dbXYVsud34AgJkj5ymcQ_IcYhLuikc9yk,6659
|
|
18
|
-
polyapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
|
-
polyapi/rendered_spec.py,sha256=uaNzBhP4cX7iGfKwzZv0dxMagWzsGeDr0cQYx_AyIhQ,2153
|
|
20
|
-
polyapi/schema.py,sha256=urHve8yg_xrtBRSa3rFxlQpVEz_B-_Xo4MHeJSIIDA4,4247
|
|
21
|
-
polyapi/server.py,sha256=NzQCZFSAJK7XiRw1kiU_i9uMvgYK7i8qh7UX2xjytJU,1908
|
|
22
|
-
polyapi/sync.py,sha256=PGdC0feBBjEVrF3d9EluW_OAxbWuzSrfh84czma8kWg,6476
|
|
23
|
-
polyapi/typedefs.py,sha256=KniVl7vwcDOhgAJmHSgTJKkP0rKWvSLIPOGsWuf9jRU,2239
|
|
24
|
-
polyapi/utils.py,sha256=Y2qMy3mf-1FNif2_IHV-ZD00OZlNmKhHN_7aPyqeWP0,8296
|
|
25
|
-
polyapi/variables.py,sha256=d36-trnfTL_8m2NkorMiImb4O3UrJbiFV38CHxV5i0A,4200
|
|
26
|
-
polyapi/webhook.py,sha256=LWv28c2MLz_OKBI_Nn7WR4C-gs1SWgbdXsoxIIf-9UI,4886
|
|
27
|
-
polyapi_python-0.3.3.dev3.dist-info/licenses/LICENSE,sha256=Hi0kDr56Dsy0uYIwNt4r9G7tI8x8miXRTlyvbeplCP8,1068
|
|
28
|
-
polyapi_python-0.3.3.dev3.dist-info/METADATA,sha256=t40qKvJPF7b1kM5CIV28jsRDofGXoTE5zUOytkAs8Lg,5580
|
|
29
|
-
polyapi_python-0.3.3.dev3.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
30
|
-
polyapi_python-0.3.3.dev3.dist-info/top_level.txt,sha256=CEFllOnzowci_50RYJac-M54KD2IdAptFsayVVF_f04,8
|
|
31
|
-
polyapi_python-0.3.3.dev3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|