generic-remote-graphql 0.0.3b4806__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.
- generic_remote_graphql/__init__.py +5 -0
- generic_remote_graphql/constants.py +32 -0
- generic_remote_graphql/generic_remote_graphql.py +109 -0
- generic_remote_graphql/graphql_requests.py +54 -0
- generic_remote_graphql/transports.py +76 -0
- generic_remote_graphql/version.py +1 -0
- generic_remote_graphql-0.0.3b4806.dist-info/METADATA +27 -0
- generic_remote_graphql-0.0.3b4806.dist-info/RECORD +10 -0
- generic_remote_graphql-0.0.3b4806.dist-info/WHEEL +5 -0
- generic_remote_graphql-0.0.3b4806.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
from .generic_remote_graphql import GenericRemoteGraphQL
|
|
2
|
+
from .transports import ApolloTransport, AppSyncTransport, GraphQLRequestError, GraphQLTransport
|
|
3
|
+
|
|
4
|
+
__all__ = ["GenericRemoteGraphQL", "AppSyncTransport", "ApolloTransport", "GraphQLTransport",
|
|
5
|
+
"GraphQLRequestError"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Constants of generic-remote-graphql (mirrors generic-remote-graphql-typescript-package)."""
|
|
2
|
+
|
|
3
|
+
from logger_local.LoggerComponentEnum import LoggerComponentEnum
|
|
4
|
+
|
|
5
|
+
# Real ids, inserted into component.component_table on 2026-11-21 (BU-4806):
|
|
6
|
+
# 5000025 = "generic-remote-graphql-python-package code", 5000026 = "... test"
|
|
7
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_ID = 5000025 # CODE component id
|
|
8
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_TEST_COMPONENT_ID = 5000026 # TEST component id
|
|
9
|
+
GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_NAME = "generic-remote-graphql-python-package"
|
|
10
|
+
DEVELOPER_EMAIL = "noy.s@circ.zone"
|
|
11
|
+
|
|
12
|
+
GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT = {
|
|
13
|
+
"component_id": GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_ID,
|
|
14
|
+
"component_name": GENERIC_REMOTE_GRAPHQL_PYTHON_COMPONENT_NAME,
|
|
15
|
+
"component_category": LoggerComponentEnum.ComponentCategory.Code.value,
|
|
16
|
+
"developer_email_address": DEVELOPER_EMAIL, # newer logger-local name ("developer_email" is deprecated)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
# Same defaults as the TypeScript package (src/constants.ts)
|
|
20
|
+
DEFAULT_NO_FILTER: dict = {}
|
|
21
|
+
DEFAULT_NEXT_TOKEN = ""
|
|
22
|
+
DEFAULT_NO_ORDER_BY: dict = {}
|
|
23
|
+
DEFAULT_LIST_ITEMS_LIMIT = 100
|
|
24
|
+
DEFAULT_MAX_PAGES = 250 # list_all stops after this many pages (protects from an endless server)
|
|
25
|
+
TEMPORARY_AUTO_USER_ID = 2 # used when no user context is given (same as TypeScript)
|
|
26
|
+
|
|
27
|
+
ORDER_BY_ASCENDING_CREATED_TIMESTAMP = {"created_timestamp": "ASC"}
|
|
28
|
+
ORDER_BY_DESCENDING_CREATED_TIMESTAMP = {"created_timestamp": "DESC"}
|
|
29
|
+
FILTER_BY_ACTIVE_ITEMS = {"end_timestamp": {"attributeExists": False}}
|
|
30
|
+
|
|
31
|
+
# Soft removal: sending any string in end_timestamp makes the server write the current time
|
|
32
|
+
END_TIMESTAMP_AUTO_NOW_VALUE = "now"
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Generic Python client for GraphQL tables (AppSync first, Apollo through the transport).
|
|
2
|
+
|
|
3
|
+
Python twin of generic-remote-graphql-typescript-package (GenericRemoteGraphQL.ts):
|
|
4
|
+
get / list / create / update / soft delete / total delete.
|
|
5
|
+
"""
|
|
6
|
+
from typing import Iterator, Optional
|
|
7
|
+
|
|
8
|
+
from . import graphql_requests as requests_text
|
|
9
|
+
from .constants import (DEFAULT_LIST_ITEMS_LIMIT, DEFAULT_MAX_PAGES, DEFAULT_NEXT_TOKEN, DEFAULT_NO_FILTER,
|
|
10
|
+
DEFAULT_NO_ORDER_BY, GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT,
|
|
11
|
+
END_TIMESTAMP_AUTO_NOW_VALUE, TEMPORARY_AUTO_USER_ID)
|
|
12
|
+
from logger_local import MetaLogger
|
|
13
|
+
from .transports import GraphQLTransport
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# mypy does not know the `object=` argument of Circles' MetaLogger (every Circles class that uses it reports this)
|
|
17
|
+
class GenericRemoteGraphQL(metaclass=MetaLogger, object=GENERIC_REMOTE_GRAPHQL_CODE_LOGGER_OBJECT): # type: ignore[call-arg] # noqa: E501
|
|
18
|
+
"""One instance = one GraphQL table.
|
|
19
|
+
|
|
20
|
+
table_name e.g. "Location" (the GraphQL type name)
|
|
21
|
+
primary_key_name e.g. "location_id"
|
|
22
|
+
transport AppSyncTransport(...) or ApolloTransport(...)
|
|
23
|
+
user_id effective user id; TEMPORARY_AUTO_USER_ID when not given (as in TypeScript)
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, *, table_name: str, primary_key_name: str, transport: GraphQLTransport,
|
|
27
|
+
list_items_limit: int = DEFAULT_LIST_ITEMS_LIMIT, user_id: Optional[int] = None,
|
|
28
|
+
is_test_data: bool = False):
|
|
29
|
+
self.table_name = table_name
|
|
30
|
+
self.primary_key_name = primary_key_name
|
|
31
|
+
self.transport = transport
|
|
32
|
+
self.list_items_limit = list_items_limit
|
|
33
|
+
self.user_id = user_id
|
|
34
|
+
# Circles rule: objects created by tests must have is_test_data = true.
|
|
35
|
+
# (The TypeScript package keeps this flag but never sends it; here create() sends it when True.)
|
|
36
|
+
self.is_test_data = is_test_data
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def _effective_user_id(self) -> int:
|
|
40
|
+
return self.user_id if self.user_id else TEMPORARY_AUTO_USER_ID
|
|
41
|
+
|
|
42
|
+
def get_by_id(self, item_id: int, return_fields: str) -> Optional[dict]:
|
|
43
|
+
query = requests_text.get_query(self.table_name, return_fields, self.primary_key_name)
|
|
44
|
+
data = self.transport.execute(query, {"id": item_id})
|
|
45
|
+
return data.get(f"get{self.table_name}")
|
|
46
|
+
|
|
47
|
+
def list_all(self, return_fields: str, filter_input: Optional[dict] = None, order_by: Optional[dict] = None,
|
|
48
|
+
page_size: Optional[int] = None, max_pages: int = DEFAULT_MAX_PAGES) -> Iterator[dict]:
|
|
49
|
+
"""Yields every item, following nextToken page after page (max_pages protects from endless loops)."""
|
|
50
|
+
next_token: Optional[str] = None
|
|
51
|
+
for _ in range(max_pages):
|
|
52
|
+
page = self.list_items(return_fields, filter_input, next_token, page_size, order_by)
|
|
53
|
+
yield from page.get("items") or []
|
|
54
|
+
next_token = page.get("nextToken")
|
|
55
|
+
if not next_token:
|
|
56
|
+
return
|
|
57
|
+
raise RuntimeError(f"list_all stopped after {max_pages} pages; the table may be huge or the server loops")
|
|
58
|
+
|
|
59
|
+
def list_items(self, return_fields: str, filter_input: Optional[dict] = None, next_token: Optional[str] = None,
|
|
60
|
+
limit: Optional[int] = None, order_by: Optional[dict] = None) -> dict:
|
|
61
|
+
"""One page. Returns {"items": [...], "nextToken": str | None}; pass nextToken back for the next page.
|
|
62
|
+
(TypeScript name: listAsync.)"""
|
|
63
|
+
token = next_token or DEFAULT_NEXT_TOKEN
|
|
64
|
+
query = requests_text.list_query(self.table_name, return_fields, token)
|
|
65
|
+
variables = {
|
|
66
|
+
"filter": dict(filter_input if filter_input is not None else DEFAULT_NO_FILTER),
|
|
67
|
+
"limit": limit or self.list_items_limit,
|
|
68
|
+
"nextToken": token,
|
|
69
|
+
"orderBy": order_by if order_by else DEFAULT_NO_ORDER_BY,
|
|
70
|
+
}
|
|
71
|
+
data = self.transport.execute(query, variables)
|
|
72
|
+
return data.get(f"list{self.table_name}s") or {"items": [], "nextToken": None}
|
|
73
|
+
|
|
74
|
+
def create(self, return_fields: str, create_input: dict) -> Optional[dict]:
|
|
75
|
+
query = requests_text.create_query(self.table_name, return_fields)
|
|
76
|
+
user_id = self._effective_user_id
|
|
77
|
+
create_data = {**create_input, "created_user_id": user_id, "updated_user_id": user_id}
|
|
78
|
+
if self.is_test_data:
|
|
79
|
+
create_data["is_test_data"] = True
|
|
80
|
+
variables = {"createInput": create_data}
|
|
81
|
+
data = self.transport.execute(query, variables)
|
|
82
|
+
return data.get(f"create{self.table_name}")
|
|
83
|
+
|
|
84
|
+
def update(self, return_fields: str, update_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
85
|
+
query = requests_text.update_query(self.table_name, return_fields)
|
|
86
|
+
# Same as TypeScript: updated_user_id is added only when we know the user (no user context = untouched)
|
|
87
|
+
update_data = {**update_input, "updated_user_id": self.user_id} if self.user_id else dict(update_input)
|
|
88
|
+
variables = {
|
|
89
|
+
"updateInput": update_data,
|
|
90
|
+
"condition": dict(condition if condition is not None else DEFAULT_NO_FILTER),
|
|
91
|
+
}
|
|
92
|
+
data = self.transport.execute(query, variables)
|
|
93
|
+
return data.get(f"update{self.table_name}")
|
|
94
|
+
|
|
95
|
+
def delete(self, return_fields: str, delete_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
96
|
+
"""Soft delete: marks the row with end_timestamp instead of removing it."""
|
|
97
|
+
# Same as TypeScript deleteAsync: updated_user_id is always sent here (temporary id without a user)
|
|
98
|
+
return self.update(return_fields,
|
|
99
|
+
{**delete_input, "end_timestamp": END_TIMESTAMP_AUTO_NOW_VALUE,
|
|
100
|
+
"updated_user_id": self._effective_user_id},
|
|
101
|
+
condition)
|
|
102
|
+
|
|
103
|
+
def total_delete(self, return_fields: str, delete_input: dict, condition: Optional[dict] = None) -> Optional[dict]:
|
|
104
|
+
"""Real delete: the row is removed from the table. Use delete() unless you really mean it."""
|
|
105
|
+
query = requests_text.delete_query(self.table_name, return_fields)
|
|
106
|
+
variables = {"deleteInput": delete_input,
|
|
107
|
+
"condition": dict(condition if condition is not None else DEFAULT_NO_FILTER)}
|
|
108
|
+
data = self.transport.execute(query, variables)
|
|
109
|
+
return data.get(f"delete{self.table_name}")
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Builds the GraphQL query text. Same shapes as the TypeScript package (src/graphQLRequests.ts)."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
from .constants import DEFAULT_NEXT_TOKEN
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_query(table_name: str, return_fields: str, id_field_name: str) -> str:
|
|
8
|
+
return f"""
|
|
9
|
+
query get{table_name}($id: Int!) {{
|
|
10
|
+
get{table_name}({id_field_name}: $id) {{
|
|
11
|
+
{return_fields}
|
|
12
|
+
}}
|
|
13
|
+
}}"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def list_query(table_name: str, return_fields: str, next_token: str = DEFAULT_NEXT_TOKEN) -> str:
|
|
17
|
+
# json.dumps makes a safe string literal (a quote inside the token cannot break the query text)
|
|
18
|
+
next_token_param = f", nextToken: {json.dumps(next_token)}" if next_token != DEFAULT_NEXT_TOKEN else ""
|
|
19
|
+
return f"""
|
|
20
|
+
query list{table_name}s($filter: Table{table_name}FilterInput, $limit: Int, $orderBy: [OrderBy{table_name}Input]) {{
|
|
21
|
+
list{table_name}s(filter: $filter, limit: $limit, orderBy: $orderBy {next_token_param}) {{
|
|
22
|
+
items {{
|
|
23
|
+
{return_fields}
|
|
24
|
+
}}
|
|
25
|
+
nextToken
|
|
26
|
+
}}
|
|
27
|
+
}}"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_query(table_name: str, return_fields: str) -> str:
|
|
31
|
+
return f"""
|
|
32
|
+
mutation create{table_name}($createInput: Create{table_name}Input!) {{
|
|
33
|
+
create{table_name}(input: $createInput) {{
|
|
34
|
+
{return_fields}
|
|
35
|
+
}}
|
|
36
|
+
}}"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def update_query(table_name: str, return_fields: str) -> str:
|
|
40
|
+
return f"""
|
|
41
|
+
mutation update{table_name}($updateInput: Update{table_name}Input!, $condition: Table{table_name}ConditionInput) {{
|
|
42
|
+
update{table_name}(input: $updateInput, condition: $condition) {{
|
|
43
|
+
{return_fields}
|
|
44
|
+
}}
|
|
45
|
+
}}"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def delete_query(table_name: str, return_fields: str) -> str:
|
|
49
|
+
return f"""
|
|
50
|
+
mutation delete{table_name}($deleteInput: Delete{table_name}Input!, $condition: Table{table_name}ConditionInput) {{
|
|
51
|
+
delete{table_name}(input: $deleteInput, condition: $condition) {{
|
|
52
|
+
{return_fields}
|
|
53
|
+
}}
|
|
54
|
+
}}"""
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""How a query travels to the server. AppSync and Apollo differ only in the authentication headers,
|
|
2
|
+
so both are a plain GraphQL-over-HTTP POST with different headers."""
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from python_sdk_remote.our_request import OurRequest
|
|
8
|
+
|
|
9
|
+
DEFAULT_TIMEOUT_SECONDS = 30
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GraphQLRequestError(Exception):
|
|
13
|
+
"""The server answered, but with GraphQL errors (response contains an "errors" list)."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, errors: list):
|
|
16
|
+
self.errors = errors
|
|
17
|
+
super().__init__(f"GraphQL errors: {errors}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GraphQLTransport(ABC):
|
|
21
|
+
"""Sends one query and returns the "data" part of the answer."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, url: str, timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
24
|
+
self.url = url
|
|
25
|
+
self.timeout = timeout
|
|
26
|
+
|
|
27
|
+
@abstractmethod
|
|
28
|
+
def headers(self) -> dict:
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def execute(self, query: str, variables: Optional[dict] = None) -> dict:
|
|
32
|
+
try:
|
|
33
|
+
# OurRequest.post (python-sdk-remote) wraps the requests library with logging, retries on 5xx and
|
|
34
|
+
# network errors, and raise_for_status. It is the Circles way (the TypeScript twin has OurAxios.post)
|
|
35
|
+
response = OurRequest.post(url=self.url, json={"query": query, "variables": variables or {}},
|
|
36
|
+
headers=self.headers(), timeout=self.timeout)
|
|
37
|
+
except requests.HTTPError as error:
|
|
38
|
+
# the server's own message (for example "UnauthorizedException") explains a 401/403 much better
|
|
39
|
+
server_text = error.response.text[:300] if error.response is not None else ""
|
|
40
|
+
raise requests.HTTPError(f"{error} | server said: {server_text}", response=error.response) from error
|
|
41
|
+
try:
|
|
42
|
+
body = response.json()
|
|
43
|
+
except ValueError as error:
|
|
44
|
+
raise GraphQLRequestError([{"message": f"answer is not JSON: {response.text[:200]}"}]) from error
|
|
45
|
+
if body.get("errors"):
|
|
46
|
+
raise GraphQLRequestError(body["errors"])
|
|
47
|
+
return body.get("data") or {}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AppSyncTransport(GraphQLTransport):
|
|
51
|
+
"""AWS AppSync with an API key (header x-api-key), like the TypeScript package."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, url: str, api_key: str, timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
54
|
+
super().__init__(url, timeout)
|
|
55
|
+
if not api_key:
|
|
56
|
+
raise ValueError("AppSync api_key is empty (look for <ENTITY>_GRAPHQL_APPSYNC_API_KEY in your .env)")
|
|
57
|
+
self._api_key = api_key
|
|
58
|
+
|
|
59
|
+
def headers(self) -> dict:
|
|
60
|
+
return {"Content-Type": "application/json", "x-api-key": self._api_key}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ApolloTransport(GraphQLTransport):
|
|
64
|
+
"""Apollo GraphQL server: optional Bearer token plus any extra headers."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, url: str, token: Optional[str] = None, extra_headers: Optional[dict] = None,
|
|
67
|
+
timeout: int = DEFAULT_TIMEOUT_SECONDS):
|
|
68
|
+
super().__init__(url, timeout)
|
|
69
|
+
self._token = token
|
|
70
|
+
self._extra_headers = dict(extra_headers or {})
|
|
71
|
+
|
|
72
|
+
def headers(self) -> dict:
|
|
73
|
+
headers = {"Content-Type": "application/json", **self._extra_headers}
|
|
74
|
+
if self._token:
|
|
75
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
76
|
+
return headers
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
PACKAGE_VERSION = "0.0.0"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: generic-remote-graphql
|
|
3
|
+
Version: 0.0.3b4806
|
|
4
|
+
Summary: PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
5
|
+
Home-page: https://github.com/circles-zone/generic-remote-graphql-python-package
|
|
6
|
+
Author: Circles
|
|
7
|
+
Author-email: info@circlez.ai
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: requests>=2.31.0
|
|
13
|
+
Requires-Dist: python-sdk-remote>=0.0.216
|
|
14
|
+
Requires-Dist: logger-local>=0.0.195
|
|
15
|
+
Dynamic: author
|
|
16
|
+
Dynamic: author-email
|
|
17
|
+
Dynamic: classifier
|
|
18
|
+
Dynamic: description
|
|
19
|
+
Dynamic: description-content-type
|
|
20
|
+
Dynamic: home-page
|
|
21
|
+
Dynamic: license
|
|
22
|
+
Dynamic: requires-dist
|
|
23
|
+
Dynamic: summary
|
|
24
|
+
|
|
25
|
+
PyPI generic-remote-graphql Python Package owned by Circlez.ai
|
|
26
|
+
JIRA Work Item: https://circles-zone.atlassian.net/browse/BU-4806
|
|
27
|
+
GHA: https://github.com/circles-zone/generic-remote-graphql-python-package/actions
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
generic_remote_graphql/__init__.py,sha256=7VydVhlz8FmcNMjOA_gi979E-h39bO5Yel_Qmow9Zho,283
|
|
2
|
+
generic_remote_graphql/constants.py,sha256=lH6BuKCyP5DpgqjgAzhQgxFEgG--5UgyAp8riEV3j8g,1663
|
|
3
|
+
generic_remote_graphql/generic_remote_graphql.py,sha256=JGYQqIhfq4-VUox8eEXJ5d8Rpah5DdrTZ7bkkI9bMbo,6321
|
|
4
|
+
generic_remote_graphql/graphql_requests.py,sha256=4-IKZHr4W6v2vmTJUGrhoFNq_sIPjkXwWqm5TT0iRmw,1939
|
|
5
|
+
generic_remote_graphql/transports.py,sha256=TLL7hiEjdvTmAOTts2OInLtuvqTuAtE0CXkq7a46hGs,3226
|
|
6
|
+
generic_remote_graphql/version.py,sha256=jYksq9tCM_NF91tQsU1-nxs4ZKEhsRoxKQFHNGc4Te8,26
|
|
7
|
+
generic_remote_graphql-0.0.3b4806.dist-info/METADATA,sha256=xt6zkI9-i_buelPLGHLuU5yUXcXGXI9z9Qzujeq1c5o,931
|
|
8
|
+
generic_remote_graphql-0.0.3b4806.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
generic_remote_graphql-0.0.3b4806.dist-info/top_level.txt,sha256=n2-QQTT-uFyKoOs6gSNYY02yd1sWlvB-IEXPWp7KdKU,23
|
|
10
|
+
generic_remote_graphql-0.0.3b4806.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
generic_remote_graphql
|