supabase-functions 0.4.2__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Joel Lee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: supabase_functions
3
+ Version: 0.4.2
4
+ Summary: Library for Supabase Functions
5
+ Home-page: https://github.com/supabase-community/functions-py
6
+ License: MIT
7
+ Author: Joel Lee
8
+ Author-email: joel@joellee.org
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Dist: httpx (>=0.24,<0.28)
18
+ Project-URL: Repository, https://github.com/supabase-community/functions-py
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Functions-py
22
+
23
+
24
+ ## Installation
25
+
26
+ `pip3 install supabase_functions`
27
+
28
+ ## Usage
29
+
30
+ Deploy your function as per documentation.
31
+
32
+
33
+ ```python3
34
+ import asyncio
35
+ from supabase_functions import AsyncFunctionsClient
36
+ async def run_func():
37
+ fc = AsyncFunctionsClient("https://<project_ref>.functions.supabase.co", {})
38
+ res = await fc.invoke("payment-sheet", {"responseType": "json"})
39
+
40
+ if __name__ == "__main__":
41
+ asyncio.run(run_func())
42
+ ```
43
+
@@ -0,0 +1,22 @@
1
+ # Functions-py
2
+
3
+
4
+ ## Installation
5
+
6
+ `pip3 install supabase_functions`
7
+
8
+ ## Usage
9
+
10
+ Deploy your function as per documentation.
11
+
12
+
13
+ ```python3
14
+ import asyncio
15
+ from supabase_functions import AsyncFunctionsClient
16
+ async def run_func():
17
+ fc = AsyncFunctionsClient("https://<project_ref>.functions.supabase.co", {})
18
+ res = await fc.invoke("payment-sheet", {"responseType": "json"})
19
+
20
+ if __name__ == "__main__":
21
+ asyncio.run(run_func())
22
+ ```
@@ -0,0 +1,44 @@
1
+ [tool.poetry]
2
+ name = "supabase_functions"
3
+ version = "0.4.2"
4
+ description = "Library for Supabase Functions"
5
+ authors = [
6
+ "Joel Lee <joel@joellee.org>",
7
+ "Andrew Smith <a.smith@silentworks.co.uk>"
8
+ ]
9
+ license = "MIT"
10
+ readme = "README.md"
11
+ repository = "https://github.com/supabase-community/functions-py"
12
+
13
+ [tool.poetry.dependencies]
14
+ python = "^3.8"
15
+ httpx = ">=0.24,<0.28"
16
+
17
+ [tool.poetry.group.dev.dependencies]
18
+ python-semantic-release = ">=8.1.1,<10.0.0"
19
+ black = ">=23.9.1,<25.0.0"
20
+ isort = "^5.12.0"
21
+ pre-commit = "^3.4.0"
22
+ pyjwt = "^2.8.0"
23
+ pytest = ">=7.4.2,<9.0.0"
24
+ pytest-cov = "^4.0.0"
25
+ unasync-cli = "^0.0.9"
26
+ pytest-asyncio = ">=0.21.1,<0.24.0"
27
+ respx = ">=0.20.2,<0.22.0"
28
+
29
+ [tool.semantic_release]
30
+ version_variables = ["supabase_functions/utils.py:__version__"]
31
+ version_toml = ["pyproject.toml:tool.poetry.version"]
32
+ major_on_zero = false
33
+ commit_message = "chore(release): bump version to v{version}"
34
+ build_command = "curl -sSL https://install.python-poetry.org | python - && export PATH=\"/github/home/.local/bin:$PATH\" && poetry install && poetry build"
35
+ upload_to_vcs_release = true
36
+ branch = "main"
37
+ changelog_components = "semantic_release.changelog.changelog_headers,semantic_release.changelog.compare_url"
38
+
39
+ [tool.pytest.ini_options]
40
+ asyncio_mode = "auto"
41
+
42
+ [build-system]
43
+ requires = ["poetry-core>=1.0.0"]
44
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Literal, Union, overload
4
+
5
+ from ._async.functions_client import AsyncFunctionsClient
6
+ from ._sync.functions_client import SyncFunctionsClient
7
+
8
+ __all__ = ["create_client"]
9
+
10
+
11
+ @overload
12
+ def create_client(
13
+ url: str, headers: dict[str, str], *, is_async: Literal[True]
14
+ ) -> AsyncFunctionsClient:
15
+ ...
16
+
17
+
18
+ @overload
19
+ def create_client(
20
+ url: str, headers: dict[str, str], *, is_async: Literal[False]
21
+ ) -> SyncFunctionsClient:
22
+ ...
23
+
24
+
25
+ def create_client(
26
+ url: str, headers: dict[str, str], *, is_async: bool
27
+ ) -> Union[AsyncFunctionsClient, SyncFunctionsClient]:
28
+ if is_async:
29
+ return AsyncFunctionsClient(url, headers)
30
+ else:
31
+ return SyncFunctionsClient(url, headers)
@@ -0,0 +1 @@
1
+ from __future__ import annotations
@@ -0,0 +1,86 @@
1
+ from typing import Any, Dict, Literal, Optional, Union
2
+
3
+ from httpx import HTTPError, Response
4
+
5
+ from ..errors import FunctionsHttpError, FunctionsRelayError
6
+ from ..utils import AsyncClient, __version__
7
+
8
+
9
+ class AsyncFunctionsClient:
10
+ def __init__(self, url: str, headers: Dict):
11
+ self.url = url
12
+ self.headers = {
13
+ "User-Agent": f"supabase-py/functions-py v{__version__}",
14
+ **headers,
15
+ }
16
+ self._client = AsyncClient(base_url=self.url, headers=self.headers)
17
+
18
+ async def _request(
19
+ self,
20
+ method: Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"],
21
+ url: str,
22
+ headers: Union[Dict[str, str], None] = None,
23
+ json: Optional[Dict[Any, Any]] = None,
24
+ ) -> Response:
25
+ response = await self._client.request(method, url, json=json, headers=headers)
26
+ try:
27
+ response.raise_for_status()
28
+ except HTTPError as exc:
29
+ raise FunctionsHttpError(
30
+ response.json().get("error")
31
+ or f"An error occurred while requesting your edge function at {exc.request.url!r}."
32
+ ) from exc
33
+
34
+ return response
35
+
36
+ def set_auth(self, token: str) -> None:
37
+ """Updates the authorization header
38
+
39
+ Parameters
40
+ ----------
41
+ token : str
42
+ the new jwt token sent in the authorization header
43
+ """
44
+
45
+ self.headers["Authorization"] = f"Bearer {token}"
46
+
47
+ async def invoke(
48
+ self, function_name: str, invoke_options: Optional[Dict] = None
49
+ ) -> Union[Dict, bytes]:
50
+ """Invokes a function
51
+
52
+ Parameters
53
+ ----------
54
+ function_name : the name of the function to invoke
55
+ invoke_options : object with the following properties
56
+ `headers`: object representing the headers to send with the request
57
+ `body`: the body of the request
58
+ `responseType`: how the response should be parsed. The default is `json`
59
+ """
60
+ headers = self.headers
61
+ if invoke_options is not None:
62
+ headers.update(invoke_options.get("headers", {}))
63
+
64
+ body = invoke_options.get("body") if invoke_options else None
65
+ response_type = (
66
+ invoke_options.get("responseType") if invoke_options else "text/plain"
67
+ )
68
+
69
+ if type(body) == str:
70
+ headers["Content-Type"] = "text/plain"
71
+ elif type(body) == dict:
72
+ headers["Content-Type"] = "application/json"
73
+
74
+ response = await self._request(
75
+ "POST", f"{self.url}/{function_name}", headers=headers, json=body
76
+ )
77
+ is_relay_error = response.headers.get("x-relay-header")
78
+
79
+ if is_relay_error and is_relay_error == "true":
80
+ raise FunctionsRelayError(response.json().get("error"))
81
+
82
+ if response_type == "json":
83
+ data = response.json()
84
+ else:
85
+ data = response.content
86
+ return data
@@ -0,0 +1 @@
1
+ from __future__ import annotations
@@ -0,0 +1,86 @@
1
+ from typing import Any, Dict, Literal, Optional, Union
2
+
3
+ from httpx import HTTPError, Response
4
+
5
+ from ..errors import FunctionsHttpError, FunctionsRelayError
6
+ from ..utils import SyncClient, __version__
7
+
8
+
9
+ class SyncFunctionsClient:
10
+ def __init__(self, url: str, headers: Dict):
11
+ self.url = url
12
+ self.headers = {
13
+ "User-Agent": f"supabase-py/functions-py v{__version__}",
14
+ **headers,
15
+ }
16
+ self._client = SyncClient(base_url=self.url, headers=self.headers)
17
+
18
+ def _request(
19
+ self,
20
+ method: Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"],
21
+ url: str,
22
+ headers: Union[Dict[str, str], None] = None,
23
+ json: Optional[Dict[Any, Any]] = None,
24
+ ) -> Response:
25
+ response = self._client.request(method, url, json=json, headers=headers)
26
+ try:
27
+ response.raise_for_status()
28
+ except HTTPError as exc:
29
+ raise FunctionsHttpError(
30
+ response.json().get("error")
31
+ or f"An error occurred while requesting your edge function at {exc.request.url!r}."
32
+ ) from exc
33
+
34
+ return response
35
+
36
+ def set_auth(self, token: str) -> None:
37
+ """Updates the authorization header
38
+
39
+ Parameters
40
+ ----------
41
+ token : str
42
+ the new jwt token sent in the authorization header
43
+ """
44
+
45
+ self.headers["Authorization"] = f"Bearer {token}"
46
+
47
+ def invoke(
48
+ self, function_name: str, invoke_options: Optional[Dict] = None
49
+ ) -> Union[Dict, bytes]:
50
+ """Invokes a function
51
+
52
+ Parameters
53
+ ----------
54
+ function_name : the name of the function to invoke
55
+ invoke_options : object with the following properties
56
+ `headers`: object representing the headers to send with the request
57
+ `body`: the body of the request
58
+ `responseType`: how the response should be parsed. The default is `json`
59
+ """
60
+ headers = self.headers
61
+ if invoke_options is not None:
62
+ headers.update(invoke_options.get("headers", {}))
63
+
64
+ body = invoke_options.get("body") if invoke_options else None
65
+ response_type = (
66
+ invoke_options.get("responseType") if invoke_options else "text/plain"
67
+ )
68
+
69
+ if type(body) == str:
70
+ headers["Content-Type"] = "text/plain"
71
+ elif type(body) == dict:
72
+ headers["Content-Type"] = "application/json"
73
+
74
+ response = self._request(
75
+ "POST", f"{self.url}/{function_name}", headers=headers, json=body
76
+ )
77
+ is_relay_error = response.headers.get("x-relay-header")
78
+
79
+ if is_relay_error and is_relay_error == "true":
80
+ raise FunctionsRelayError(response.json().get("error"))
81
+
82
+ if response_type == "json":
83
+ data = response.json()
84
+ else:
85
+ data = response.content
86
+ return data
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TypedDict
4
+
5
+
6
+ class FunctionsApiErrorDict(TypedDict):
7
+ name: str
8
+ message: str
9
+ status: int
10
+
11
+
12
+ class FunctionsError(Exception):
13
+ def __init__(self, message: str, name: str, status: int) -> None:
14
+ super().__init__(message)
15
+ self.message = message
16
+ self.name = name
17
+ self.status = status
18
+
19
+ def to_dict(self) -> FunctionsApiErrorDict:
20
+ return {
21
+ "name": self.name,
22
+ "message": self.message,
23
+ "status": self.status,
24
+ }
25
+
26
+
27
+ class FunctionsHttpError(FunctionsError):
28
+ def __init__(self, message: str) -> None:
29
+ super().__init__(
30
+ message,
31
+ "FunctionsHttpError",
32
+ 400,
33
+ )
34
+
35
+
36
+ class FunctionsRelayError(FunctionsError):
37
+ """Base exception for relay errors."""
38
+
39
+ def __init__(self, message: str) -> None:
40
+ super().__init__(
41
+ message,
42
+ "FunctionsRelayError",
43
+ 400,
44
+ )
@@ -0,0 +1,9 @@
1
+ from httpx import AsyncClient as AsyncClient # noqa: F401
2
+ from httpx import Client as BaseClient
3
+
4
+ __version__ = "0.4.2"
5
+
6
+
7
+ class SyncClient(BaseClient):
8
+ def aclose(self) -> None:
9
+ self.close()