polyapi-python 0.2.4.dev13__tar.gz → 0.2.5.dev2__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.
Files changed (38) hide show
  1. {polyapi_python-0.2.4.dev13/polyapi_python.egg-info → polyapi_python-0.2.5.dev2}/PKG-INFO +1 -1
  2. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/api.py +2 -0
  3. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/auth.py +3 -3
  4. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/cli.py +2 -1
  5. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/constants.py +4 -0
  6. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/function_cli.py +2 -0
  7. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/generate.py +7 -23
  8. polyapi_python-0.2.5.dev2/polyapi/rendered_spec.py +34 -0
  9. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/server.py +3 -1
  10. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/typedefs.py +1 -0
  11. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/utils.py +24 -1
  12. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/webhook.py +19 -4
  13. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2/polyapi_python.egg-info}/PKG-INFO +1 -1
  14. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi_python.egg-info/SOURCES.txt +1 -0
  15. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/pyproject.toml +1 -1
  16. polyapi_python-0.2.5.dev2/tests/test_utils.py +17 -0
  17. polyapi_python-0.2.4.dev13/tests/test_utils.py +0 -10
  18. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/LICENSE +0 -0
  19. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/README.md +0 -0
  20. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/__init__.py +0 -0
  21. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/__main__.py +0 -0
  22. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/client.py +0 -0
  23. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/config.py +0 -0
  24. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/error_handler.py +0 -0
  25. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/exceptions.py +0 -0
  26. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/execute.py +0 -0
  27. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/py.typed +0 -0
  28. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/schema.py +0 -0
  29. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi/variables.py +0 -0
  30. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi_python.egg-info/dependency_links.txt +0 -0
  31. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi_python.egg-info/requires.txt +0 -0
  32. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/polyapi_python.egg-info/top_level.txt +0 -0
  33. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/setup.cfg +0 -0
  34. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/tests/test_api.py +0 -0
  35. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/tests/test_auth.py +0 -0
  36. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/tests/test_function_cli.py +0 -0
  37. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/tests/test_server.py +0 -0
  38. {polyapi_python-0.2.4.dev13 → polyapi_python-0.2.5.dev2}/tests/test_variables.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: polyapi-python
3
- Version: 0.2.4.dev13
3
+ Version: 0.2.5.dev2
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
@@ -24,6 +24,8 @@ def {function_name}(
24
24
  \"""
25
25
  resp = execute("{function_type}", "{function_id}", {data})
26
26
  return {api_response_type}(resp.json()) # type: ignore
27
+
28
+
27
29
  """
28
30
 
29
31
 
@@ -16,9 +16,9 @@ import asyncio
16
16
 
17
17
 
18
18
  class AuthFunctionResponse(TypedDict):
19
- status: int
20
- data: Any
21
- headers: Dict[str, str]
19
+ status: int
20
+ data: Any
21
+ headers: Dict[str, str]
22
22
 
23
23
 
24
24
  async def getToken(clientId: str, clientSecret: str, scopes: List[str], callback, options: Optional[Dict[str, Any]] = None):
@@ -3,8 +3,9 @@ import argparse
3
3
  from polyapi.utils import print_green
4
4
 
5
5
  from .config import clear_config, set_api_key_and_url
6
- from .generate import generate, clear, save_rendered_specs
6
+ from .generate import generate, clear
7
7
  from .function_cli import function_add_or_update
8
+ from .rendered_spec import save_rendered_specs
8
9
 
9
10
 
10
11
  CLI_COMMANDS = ["setup", "generate", "function", "clear", "help", "save_rendered_specs"]
@@ -5,6 +5,8 @@ JSONSCHEMA_TO_PYTHON_TYPE_MAP = {
5
5
  "boolean": "bool",
6
6
  "array": "List",
7
7
  "object": "Dict",
8
+ "function": "Callable",
9
+ "void": "None",
8
10
  }
9
11
 
10
12
 
@@ -15,6 +17,8 @@ PYTHON_TO_JSONSCHEMA_TYPE_MAP = {
15
17
  "bool": "boolean",
16
18
  "List": "array",
17
19
  "Dict": "object",
20
+ "Callable": "function",
21
+ "None": "void",
18
22
  }
19
23
 
20
24
  BASIC_PYTHON_TYPES = set(PYTHON_TO_JSONSCHEMA_TYPE_MAP.keys())
@@ -13,6 +13,7 @@ from importlib.metadata import packages_distributions
13
13
  from polyapi.generate import get_functions_and_parse, generate_functions
14
14
  from polyapi.config import get_api_key_and_url
15
15
  from polyapi.constants import PYTHON_TO_JSONSCHEMA_TYPE_MAP
16
+ # from polyapi.rendered_spec import update_rendered_spec
16
17
  from polyapi.utils import get_auth_headers, print_green, print_red, print_yellow
17
18
  import importlib
18
19
 
@@ -270,6 +271,7 @@ def function_add_or_update(
270
271
  print(f"Function ID: {function_id}")
271
272
  print("Generating new custom function...", end="")
272
273
  functions = get_functions_and_parse(limit_ids=[function_id])
274
+ # update_rendered_spec(functions[0])
273
275
  generate_functions(functions)
274
276
  print_green("DONE")
275
277
  else:
@@ -6,7 +6,6 @@ from typing import List
6
6
 
7
7
  from polyapi.auth import render_auth_function
8
8
  from polyapi.client import render_client_function
9
- from polyapi.execute import execute_post
10
9
  from polyapi.webhook import render_webhook_handle
11
10
 
12
11
  from .typedefs import PropertySpecification, SpecificationDto, VariableSpecDto
@@ -75,11 +74,14 @@ def cache_specs(specs: List[SpecificationDto]):
75
74
 
76
75
  full_path = os.path.dirname(os.path.abspath(__file__))
77
76
  full_path = os.path.join(full_path, "poly")
78
- if not os.path.exists(full_path):
79
- os.makedirs(full_path)
77
+ try:
78
+ if not os.path.exists(full_path):
79
+ os.makedirs(full_path)
80
80
 
81
- with open(os.path.join(full_path, "specs.json"), "w") as f:
82
- f.write(json.dumps(supported))
81
+ with open(os.path.join(full_path, "specs.json"), "w") as f:
82
+ f.write(json.dumps(supported))
83
+ except Exception as e:
84
+ print("Failed to cache specs", e)
83
85
 
84
86
 
85
87
  def read_cached_specs() -> List[SpecificationDto]:
@@ -154,24 +156,6 @@ def clear() -> None:
154
156
  print("Cleared!")
155
157
 
156
158
 
157
- def save_rendered_specs() -> None:
158
- specs = read_cached_specs()
159
- # right now we just support rendered apiFunctions
160
- api_specs = [spec for spec in specs if spec["type"] == "apiFunction"]
161
- for spec in api_specs:
162
- assert spec["function"]
163
- func_str, type_defs = render_spec(spec)
164
- data = {
165
- "language": "python",
166
- "apiFunctionId": spec["id"],
167
- "signature": func_str,
168
- "typedefs": type_defs,
169
- }
170
- resp = execute_post("/functions/rendered-specs", data)
171
- print("adding", spec["context"], spec["name"])
172
- assert resp.status_code == 201, (resp.text, resp.status_code)
173
-
174
-
175
159
  def render_spec(spec: SpecificationDto):
176
160
  function_type = spec["type"]
177
161
  function_description = spec["description"]
@@ -0,0 +1,34 @@
1
+ from typing import Dict
2
+ from polyapi.generate import read_cached_specs, render_spec
3
+ from polyapi.execute import execute_post
4
+ from polyapi.typedefs import SpecificationDto
5
+
6
+
7
+ def update_rendered_spec(spec: SpecificationDto):
8
+ print("Updating rendered spec...")
9
+ func_str, type_defs = render_spec(spec)
10
+ data = {
11
+ "language": "python",
12
+ "signature": func_str,
13
+ "typedefs": type_defs,
14
+ }
15
+ if spec["type"] == "apiFunction":
16
+ data["apiFunctionId"] = spec["id"]
17
+ elif spec["type"] == "serverFunction":
18
+ data["customFunctionId"] = spec["id"]
19
+ else:
20
+ raise NotImplementedError("todo")
21
+
22
+ resp = execute_post("/functions/rendered-specs", data)
23
+ assert resp.status_code == 201, (resp.text, resp.status_code)
24
+ # this needs to run with something like `kn func run...`
25
+
26
+
27
+ def save_rendered_specs() -> None:
28
+ specs = read_cached_specs()
29
+ # right now we just support rendered apiFunctions
30
+ api_specs = [spec for spec in specs if spec["type"] == "apiFunction"]
31
+ for spec in api_specs:
32
+ assert spec["function"]
33
+ print("adding", spec["context"], spec["name"])
34
+ update_rendered_spec(spec)
@@ -4,7 +4,7 @@ from polyapi.typedefs import PropertySpecification
4
4
  from polyapi.utils import camelCase, add_type_import_path, parse_arguments, get_type_and_def
5
5
 
6
6
  SERVER_DEFS_TEMPLATE = """
7
- from typing import List, Dict, Any, TypedDict
7
+ from typing import List, Dict, Any, TypedDict, Callable
8
8
  {args_def}
9
9
  {return_type_def}
10
10
  """
@@ -22,6 +22,8 @@ def {function_name}(
22
22
  return {return_action}
23
23
  except:
24
24
  return resp.text
25
+
26
+
25
27
  """
26
28
 
27
29
 
@@ -12,6 +12,7 @@ class PropertySpecification(TypedDict):
12
12
 
13
13
  class PropertyType(TypedDict):
14
14
  kind: Literal['void', 'primitive', 'array', 'object', 'function', 'plain']
15
+ spec: NotRequired[Dict]
15
16
  name: NotRequired[str]
16
17
  type: NotRequired[str]
17
18
  items: NotRequired['PropertyType']
@@ -10,7 +10,7 @@ from polyapi.schema import generate_schema_types, clean_title, map_primitive_typ
10
10
 
11
11
  # this string should be in every __init__ file.
12
12
  # it contains all the imports needed for the function or variable code to run
13
- CODE_IMPORTS = "from typing import List, Dict, Any, TypedDict, Optional\nimport logging\nimport requests\nimport socketio # type: ignore\nfrom polyapi.config import get_api_key_and_url\nfrom polyapi.execute import execute, execute_post, variable_get, variable_update\n\n"
13
+ CODE_IMPORTS = "from typing import List, Dict, Any, TypedDict, Optional, Callable\nimport logging\nimport requests\nimport socketio # type: ignore\nfrom polyapi.config import get_api_key_and_url\nfrom polyapi.execute import execute, execute_post, variable_get, variable_update\n\n"
14
14
 
15
15
 
16
16
  def init_the_init(full_path: str) -> None:
@@ -61,6 +61,10 @@ def print_red(s: str):
61
61
  def add_type_import_path(function_name: str, arg: str) -> str:
62
62
  """ if not basic type, coerce to camelCase and add the import path
63
63
  """
64
+ # for now, just treat Callables as basic types
65
+ if arg.startswith("Callable"):
66
+ return arg
67
+
64
68
  if arg in BASIC_PYTHON_TYPES:
65
69
  return arg
66
70
 
@@ -142,6 +146,25 @@ def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
142
146
  return "Any", ""
143
147
  else:
144
148
  return "Dict", ""
149
+ elif type_spec["kind"] == "function":
150
+ arg_types = []
151
+ arg_defs = []
152
+ if "spec" in type_spec:
153
+ return_type, _ = get_type_and_def(type_spec["spec"]["returnType"])
154
+ if return_type not in BASIC_PYTHON_TYPES:
155
+ # for now only Python only supports basic types as return types
156
+ return_type = "Any"
157
+
158
+ for argument in type_spec["spec"]["arguments"]:
159
+ arg_type, arg_def = get_type_and_def(argument["type"])
160
+ arg_types.append(arg_type)
161
+ if arg_def:
162
+ arg_defs.append(arg_def)
163
+
164
+ final_arg_type = "Callable[[{}], {}]".format(", ".join(arg_types), return_type)
165
+ return final_arg_type, "\n".join(arg_defs)
166
+ else:
167
+ return "Callable", ""
145
168
  elif type_spec["kind"] == "any":
146
169
  return "Any", ""
147
170
  else:
@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Tuple
6
6
 
7
7
  from polyapi.config import get_api_key_and_url
8
8
  from polyapi.typedefs import PropertySpecification
9
- from polyapi.utils import poly_full_path
9
+ from polyapi.utils import parse_arguments, poly_full_path
10
10
 
11
11
  # all active webhook handlers, used by unregister_all to cleanup
12
12
  active_handlers: List[Dict[str, Any]] = []
@@ -15,10 +15,18 @@ active_handlers: List[Dict[str, Any]] = []
15
15
  client = None
16
16
 
17
17
 
18
+ WEBHOOK_DEFS_TEMPLATE = """
19
+ from typing import List, Dict, Any, TypedDict, Callable
20
+ {function_args_def}
21
+ """
22
+
23
+
18
24
  WEBHOOK_TEMPLATE = """
19
25
 
20
26
 
21
- async def {function_name}(callback, options=None):
27
+ async def {function_name}(
28
+ {function_args}
29
+ ):
22
30
  \"""{description}
23
31
 
24
32
  Function ID: {function_id}
@@ -112,15 +120,22 @@ def render_webhook_handle(
112
120
  arguments: List[PropertySpecification],
113
121
  return_type: Dict[str, Any],
114
122
  ) -> Tuple[str, str]:
123
+ function_args, function_args_def = parse_arguments(function_name, arguments)
124
+
125
+ if "WebhookEventType" in function_args:
126
+ # let's add the function name import!
127
+ function_args = function_args.replace("WebhookEventType", f"_{function_name}.WebhookEventType")
128
+
115
129
  func_str = WEBHOOK_TEMPLATE.format(
116
130
  description=function_description,
117
131
  client_id=uuid.uuid4().hex,
118
132
  function_id=function_id,
119
133
  function_name=function_name,
134
+ function_args=function_args,
120
135
  function_path=poly_full_path(function_context, function_name),
121
136
  )
122
-
123
- return func_str, ""
137
+ func_defs = WEBHOOK_DEFS_TEMPLATE.format(function_args_def=function_args_def)
138
+ return func_str, func_defs
124
139
 
125
140
 
126
141
  def start(*args):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: polyapi-python
3
- Version: 0.2.4.dev13
3
+ Version: 0.2.5.dev2
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
@@ -15,6 +15,7 @@ polyapi/execute.py
15
15
  polyapi/function_cli.py
16
16
  polyapi/generate.py
17
17
  polyapi/py.typed
18
+ polyapi/rendered_spec.py
18
19
  polyapi/schema.py
19
20
  polyapi/server.py
20
21
  polyapi/typedefs.py
@@ -3,7 +3,7 @@ requires = ["setuptools>=61.2", "wheel"]
3
3
 
4
4
  [project]
5
5
  name = "polyapi-python"
6
- version = "0.2.4.dev13"
6
+ version = "0.2.5.dev2"
7
7
  description = "The Python Client for PolyAPI, the IPaaS by Developers for Developers"
8
8
  authors = [{ name = "Dan Fellin", email = "dan@polyapi.io" }]
9
9
  dependencies = [
@@ -0,0 +1,17 @@
1
+ import unittest
2
+ from polyapi.schema import _fix_title
3
+ from polyapi.utils import get_type_and_def
4
+
5
+ OPENAPI_FUNCTION = {'kind': 'function', 'spec': {'arguments': [{'name': 'event', 'required': False, 'type': {'kind': 'object', 'schema': {'$schema': 'http://json-schema.org/draft-06/schema#', 'type': 'array', 'items': {'$ref': '#/definitions/WebhookEventTypeElement'}, 'definitions': {'WebhookEventTypeElement': {'type': 'object', 'additionalProperties': False, 'properties': {'title': {'type': 'string'}, 'manufacturerName': {'type': 'string'}, 'carType': {'type': 'string'}, 'id': {'type': 'integer'}}, 'required': ['carType', 'id', 'manufacturerName', 'title'], 'title': 'WebhookEventTypeElement'}}}}}, {'name': 'headers', 'required': False, 'type': {'kind': 'object', 'typeName': 'Record<string, any>'}}, {'name': 'params', 'required': False, 'type': {'kind': 'object', 'typeName': 'Record<string, any>'}}, {'name': 'polyCustom', 'required': False, 'type': {'kind': 'object', 'properties': [{'name': 'responseStatusCode', 'type': {'type': 'number', 'kind': 'primitive'}, 'required': True}, {'name': 'responseContentType', 'type': {'type': 'string', 'kind': 'primitive'}, 'required': True, 'nullable': True}]}}], 'returnType': {'kind': 'void'}, 'synchronous': True}}
6
+
7
+
8
+ class T(unittest.TestCase):
9
+ def test_fix_titles(self):
10
+ input_data = {'properties': {'requestNumber': {'title': 'Requestnumber', 'type': 'integer'}}, 'required': ['requestNumber'], 'title': 'numOfCars', 'type': 'object', 'metadata': {'pydantic.internal.needs_apply_discriminated_union': False}}
11
+ output = 'from typing import TypedDict\nfrom typing_extensions import Required\n\n\nclass Numofcars(TypedDict, total=False):\n """ numOfCars. """\n\n requestNumber: Required[int]\n """\n Requestnumber.\n\n Required property\n """\n\n'
12
+ fixed = _fix_title(input_data, output)
13
+ self.assertIn("class numOfCars", fixed)
14
+
15
+ def test_get_type_and_def(self):
16
+ arg_type, arg_def = get_type_and_def(OPENAPI_FUNCTION)
17
+ self.assertEqual(arg_type, "Callable[[List[WebhookEventTypeElement], Dict, Dict, Dict], None]")
@@ -1,10 +0,0 @@
1
- import unittest
2
- from polyapi.schema import _fix_title
3
-
4
-
5
- class T(unittest.TestCase):
6
- def test_fix_titles(self):
7
- input_data = {'properties': {'requestNumber': {'title': 'Requestnumber', 'type': 'integer'}}, 'required': ['requestNumber'], 'title': 'numOfCars', 'type': 'object', 'metadata': {'pydantic.internal.needs_apply_discriminated_union': False}}
8
- output = 'from typing import TypedDict\nfrom typing_extensions import Required\n\n\nclass Numofcars(TypedDict, total=False):\n """ numOfCars. """\n\n requestNumber: Required[int]\n """\n Requestnumber.\n\n Required property\n """\n\n'
9
- fixed = _fix_title(input_data, output)
10
- self.assertIn("class numOfCars", fixed)