Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions polyapi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def execute_from_cli() -> None:
parser.add_argument("--client", action="store_true", help="Pass --client when adding function to add a client function.")
parser.add_argument("--server", action="store_true", help="Pass --server when adding function to add a server function.")
parser.add_argument("--logs", action="store_true", help="Pass --logs when adding function if you want to store and see the function logs.")
parser.add_argument("--skip-generate", action="store_true", help="Pass --skip-generate to skip generating the library after adding a function.")
parser.add_argument("command", choices=CLI_COMMANDS)
parser.add_argument("subcommands", nargs="*")
args = parser.parse_args()
Expand All @@ -44,8 +45,8 @@ def execute_from_cli() -> None:
clear_config()
generate()
elif command == "update_rendered_spec":
assert len(args.subcommands) == 2
updated = get_and_update_rendered_spec(args.subcommands[0], args.subcommands[1])
assert len(args.subcommands) == 1
updated = get_and_update_rendered_spec(args.subcommands[0])
if updated:
print("Updated rendered spec!")
else:
Expand All @@ -55,4 +56,4 @@ def execute_from_cli() -> None:
print("Clearing the generated library...")
clear()
elif command == "function":
function_add_or_update(args.context, args.description, args.client, args.server, args.logs, args.subcommands)
function_add_or_update(args.context, args.description, args.client, args.server, args.logs, args.subcommands, not args.skip_generate)
10 changes: 6 additions & 4 deletions polyapi/function_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ def function_add_or_update(
server: bool,
logs_enabled: bool,
subcommands: List,
generate: bool = True,
):
parser = argparse.ArgumentParser()
parser.add_argument("subcommand", choices=["add"])
Expand Down Expand Up @@ -268,10 +269,11 @@ def function_add_or_update(
print_green("DEPLOYED")
function_id = resp.json()["id"]
print(f"Function ID: {function_id}")
print("Generating new custom function...", end="")
functions = get_functions_and_parse(limit_ids=[function_id])
generate_functions(functions)
print_green("DONE")
if generate:
print("Generating new custom function...", end="")
functions = get_functions_and_parse(limit_ids=[function_id])
generate_functions(functions)
print_green("DONE")
else:
print("Error adding function.")
print(resp.status_code)
Expand Down
6 changes: 3 additions & 3 deletions polyapi/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .typedefs import PropertySpecification, SpecificationDto, VariableSpecDto
from .api import render_api_function
from .server import render_server_function
from .utils import add_import_to_init, get_auth_headers, init_the_init
from .utils import add_import_to_init, get_auth_headers, init_the_init, to_func_namespace
from .variables import generate_variables
from .config import get_api_key_and_url, initialize_config

Expand Down Expand Up @@ -232,10 +232,10 @@ def add_function_file(
# add function to init
init_path = os.path.join(full_path, "__init__.py")
with open(init_path, "a") as f:
f.write(f"\n\nfrom . import _{function_name}\n\n{func_str}")
f.write(f"\n\nfrom . import {to_func_namespace(function_name)}\n\n{func_str}")

# add type_defs to underscore file
file_path = os.path.join(full_path, f"_{function_name}.py")
file_path = os.path.join(full_path, f"{to_func_namespace(function_name)}.py")
with open(file_path, "w") as f:
f.write(func_type_defs)

Expand Down
21 changes: 8 additions & 13 deletions polyapi/rendered_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from polyapi.typedefs import SpecificationDto


def update_rendered_spec(api_key: str, spec: SpecificationDto):
def update_rendered_spec(spec: SpecificationDto):
print("Updating rendered spec...")
func_str, type_defs = render_spec(spec)
data = {
Expand All @@ -27,21 +27,16 @@ def update_rendered_spec(api_key: str, spec: SpecificationDto):
raise NotImplementedError("todo")

# use super key on develop-k8s here!
_, base_url = get_api_key_and_url()
if not base_url:
base_url = os.environ.get("HOST_URL")
api_key, base_url = get_api_key_and_url()

url = f"{base_url}/functions/rendered-specs"
headers = {"Authorization": f"Bearer {api_key}"}
resp = requests.post(url, json=data, headers=headers)
assert resp.status_code == 201, (resp.text, resp.status_code)


def _get_spec(api_key: str, spec_id: str) -> Optional[SpecificationDto]:
_, base_url = get_api_key_and_url()
if not base_url:
base_url = os.environ.get("HOST_URL")

def _get_spec(spec_id: str) -> Optional[SpecificationDto]:
api_key, base_url = get_api_key_and_url()
url = f"{base_url}/specs"
headers = {"Authorization": f"Bearer {api_key}"}
resp = requests.get(url, headers=headers)
Expand All @@ -55,10 +50,10 @@ def _get_spec(api_key: str, spec_id: str) -> Optional[SpecificationDto]:
raise NotImplementedError(resp.content)


def get_and_update_rendered_spec(api_key: str, spec_id: str) -> bool:
spec = _get_spec(api_key, spec_id)
def get_and_update_rendered_spec(spec_id: str) -> bool:
spec = _get_spec(spec_id)
if spec:
update_rendered_spec(api_key, spec)
update_rendered_spec(spec)
return True
return False

Expand All @@ -70,4 +65,4 @@ def save_rendered_specs() -> None:
for spec in api_specs:
assert spec["function"]
print("adding", spec["context"], spec["name"])
update_rendered_spec("FIXME", spec)
update_rendered_spec(spec)
22 changes: 18 additions & 4 deletions polyapi/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ def add_type_import_path(function_name: str, arg: str) -> str:
else:
if '"' in sub:
sub = sub.replace('"', "")
return f'List["_{function_name}.{camelCase(sub)}"]'
return f'List["{to_func_namespace(function_name)}.{camelCase(sub)}"]'
else:
return f'List[_{function_name}.{camelCase(sub)}]'
return f'List[{to_func_namespace(function_name)}.{camelCase(sub)}]'

return f'_{function_name}.{camelCase(arg)}'
return f'{to_func_namespace(function_name)}.{camelCase(arg)}'


def get_type_and_def(type_spec: PropertyType) -> Tuple[str, str]:
Expand Down Expand Up @@ -183,4 +183,18 @@ def poly_full_path(context, name) -> str:
path = context + "." + name
else:
path = name
return f"poly.{path}"
return f"poly.{path}"


RESERVED_TYPES = {"List", "Dict", "Any", "Optional", "Callable"}


def to_func_namespace(s: str) -> str:
""" convert a function name to some function namespace
by default it is
"""
rv = s[0].upper() + s[1:]
if rv in RESERVED_TYPES:
return "_" + rv
else:
return rv
4 changes: 2 additions & 2 deletions polyapi/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from polyapi.config import get_api_key_and_url
from polyapi.typedefs import PropertySpecification
from polyapi.utils import parse_arguments, poly_full_path
from polyapi.utils import parse_arguments, poly_full_path, to_func_namespace

# all active webhook handlers, used by unregister_all to cleanup
active_handlers: List[Dict[str, Any]] = []
Expand Down Expand Up @@ -124,7 +124,7 @@ def render_webhook_handle(

if "WebhookEventType" in function_args:
# let's add the function name import!
function_args = function_args.replace("WebhookEventType", f"_{function_name}.WebhookEventType")
function_args = function_args.replace("WebhookEventType", f"{to_func_namespace(function_name)}.WebhookEventType")

func_str = WEBHOOK_TEMPLATE.format(
description=function_description,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ requires = ["setuptools>=61.2", "wheel"]

[project]
name = "polyapi-python"
version = "0.2.5"
version = "0.2.6"
description = "The Python Client for PolyAPI, the IPaaS by Developers for Developers"
authors = [{ name = "Dan Fellin", email = "[email protected]" }]
dependencies = [
Expand Down
9 changes: 5 additions & 4 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest

from polyapi.api import render_api_function
from polyapi.utils import to_func_namespace

ACCUWEATHER = {
"id": "f7588018-2364-4586-b60d",
Expand Down Expand Up @@ -235,7 +236,7 @@ def test_render_function_accuweather(self):
)
self.assertIn(ACCUWEATHER["id"], func_str)
self.assertIn("locationId: int,", func_str)
self.assertIn(f"-> _{name}.{name}Response", func_str)
self.assertIn(f"-> {to_func_namespace(name)}.{name}Response", func_str)

def test_render_function_zillow(self):
name = ZILLOW["name"]
Expand All @@ -249,7 +250,7 @@ def test_render_function_zillow(self):
)
self.assertIn(ZILLOW["id"], func_str)
self.assertIn("locationId: int,", func_str)
self.assertIn(f"-> _{name}.{name}Response", func_str)
self.assertIn(f"-> {to_func_namespace(name)}.{name}Response", func_str)

def test_render_function_twilio_api(self):
name = TWILIO["name"]
Expand All @@ -264,7 +265,7 @@ def test_render_function_twilio_api(self):
self.assertIn(TWILIO["id"], func_str)
self.assertIn("conversationSID: str", func_str)
self.assertIn("authToken: str", func_str)
self.assertIn(f"-> _{name}.{name}Response", func_str)
self.assertIn(f"-> {to_func_namespace(name)}.{name}Response", func_str)

def test_render_function_twilio_get_details(self):
# same test but try it as a serverFunction rather than an apiFunction
Expand All @@ -278,6 +279,6 @@ def test_render_function_twilio_get_details(self):
TWILIO_GET_DETAILS["function"]["returnType"],
)
self.assertIn(TWILIO_GET_DETAILS["id"], func_str)
self.assertIn(f"-> _{name}.{name}Response", func_str)
self.assertIn(f"-> {to_func_namespace(name)}.{name}Response", func_str)
self.assertIn("class SubresourceUris", func_type_defs)
# self.assertIn('Required["SubresourceUris"]', func_type_defs)
1 change: 0 additions & 1 deletion tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,3 @@ def test_render_get_token(self):
self.assertIn(GET_TOKEN["id"], func_str)
# self.assertIn("conversationSID: str", func_str)
# self.assertIn("authToken: str", func_str)
# self.assertIn(f"-> _{name}.ResponseType", func_str)
4 changes: 3 additions & 1 deletion tests/test_server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import unittest

from polyapi.utils import to_func_namespace

from .test_api import TWILIO
from polyapi.server import render_server_function

Expand Down Expand Up @@ -45,7 +47,7 @@ def test_render_function_twilio_server(self):
self.assertIn(TWILIO["id"], func_str)
self.assertIn("conversationSID: str", func_str)
self.assertIn("authToken: str", func_str)
self.assertIn(f"-> _{name}.ResponseType", func_str)
self.assertIn(f"-> {to_func_namespace(name)}.ResponseType", func_str)

def test_render_function_get_products_count(self):
return_type = GET_PRODUCTS_COUNT["function"]["returnType"]
Expand Down