-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
91 lines (76 loc) · 2.72 KB
/
api.py
File metadata and controls
91 lines (76 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from typing import Any, Dict, List, Tuple
from polyapi.typedefs import PropertySpecification
from polyapi.utils import add_type_import_path, parse_arguments, get_type_and_def, rewrite_arg_name
API_DEFS_TEMPLATE = """
from typing import List, Dict, Any, TypedDict
{args_def}
{return_type_def}
class {api_response_type}(TypedDict):
status: int
headers: Dict
data: {return_type_name}
"""
API_FUNCTION_TEMPLATE = """
def {function_name}(
{args}
) -> {api_response_type}:
\"""{function_description}
Function ID: {function_id}
\"""
if get_direct_execute_config():
resp = direct_execute("{function_type}", "{function_id}", {data})
return {api_response_type}({{
"status": resp.status_code,
"headers": dict(resp.headers),
"data": resp.json()
}}) # type: ignore
else:
resp = execute("{function_type}", "{function_id}", {data})
return {api_response_type}(resp.json()) # type: ignore
async def {function_name}_async(
{args}
) -> {api_response_type}:
\"""{function_description}
Function ID: {function_id}
\"""
if get_direct_execute_config():
resp = await direct_execute_async("{function_type}", "{function_id}", {data})
return {api_response_type}({{
"status": resp.status_code,
"headers": dict(resp.headers),
"data": resp.json()
}}) # type: ignore
else:
resp = await execute_async("{function_type}", "{function_id}", {data})
return {api_response_type}(resp.json()) # type: ignore
"""
def render_api_function(
function_type: str,
function_name: str,
function_id: str,
function_description: str,
arguments: List[PropertySpecification],
return_type: Dict[str, Any],
) -> Tuple[str, str]:
assert function_type == "apiFunction"
arg_names = [a["name"] for a in arguments]
args, args_def = parse_arguments(function_name, arguments)
return_type_name, return_type_def = get_type_and_def(return_type) # type: ignore
data = "{" + ", ".join([f"'{arg}': {rewrite_arg_name(arg)}" for arg in arg_names]) + "}"
api_response_type = f"{function_name}Response"
func_type_defs = API_DEFS_TEMPLATE.format(
args_def=args_def,
api_response_type=api_response_type,
return_type_name=return_type_name,
return_type_def=return_type_def,
)
func_str = API_FUNCTION_TEMPLATE.format(
function_type="api",
function_name=function_name,
function_id=function_id,
function_description=function_description.replace('"', "'"),
args=args,
data=data,
api_response_type=add_type_import_path(function_name, api_response_type),
)
return func_str, func_type_defs