-
Notifications
You must be signed in to change notification settings - Fork 296
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implements the start of an SDK for Python Workers.
- Loading branch information
Showing
2 changed files
with
76 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
# This module defines a Workers API for Python. It is similar to the API provided by | ||
# JS Workers, but with changes and additions to be more idiomatic to the Python | ||
# programming language. | ||
from http import HTTPMethod, HTTPStatus | ||
from typing import TypedDict, Unpack | ||
|
||
import js | ||
|
||
from pyodide.http import FetchResponse, pyfetch | ||
|
||
JSBody = ( | ||
"js.Blob | js.ArrayBuffer | js.TypedArray | js.DataView | js.FormData |" | ||
"js.ReadableStream | js.URLSearchParams" | ||
) | ||
Body = "str | JSBody" | ||
Headers = dict[str, str] | list[tuple[str, str]] | ||
|
||
|
||
class FetchKwargs(TypedDict, total=False): | ||
headers: Headers | None | ||
body: "Body | None" | ||
method: HTTPMethod = HTTPMethod.GET | ||
|
||
|
||
async def fetch( | ||
resource: str, | ||
**other_options: Unpack[FetchKwargs], | ||
) -> FetchResponse: | ||
if "method" in other_options and isinstance(other_options["method"], HTTPMethod): | ||
other_options["method"] = other_options["method"].value | ||
return await pyfetch(resource, **other_options) | ||
|
||
|
||
def Response( | ||
body: Body, | ||
status: HTTPStatus | int = HTTPStatus.OK, | ||
statusText="", | ||
headers: Headers = None, | ||
) -> js.Response: | ||
""" | ||
Represents the response to a request. | ||
Based on the JS API of the same name: | ||
https://developer.mozilla.org/en-US/docs/Web/API/Response/Response. | ||
""" | ||
options = { | ||
"status": status.value if isinstance(status, HTTPStatus) else status, | ||
} | ||
if len(statusText) > 0: | ||
options["statusText"] = statusText | ||
if headers: | ||
if isinstance(headers, list): | ||
# We should have a list[tuple[str, str]] | ||
options["headers"] = js.Headers.new(headers) | ||
elif isinstance(headers, dict): | ||
options["headers"] = js.Headers.new(headers.items()) | ||
else: | ||
raise AssertionError( | ||
"Response() received unexpected type for headers argument" | ||
) | ||
|
||
return js.Response.new(body, **options) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters