Skip to content

Commit 9ec828f

Browse files
authored
Python: Make fetch work with Python Request as argument (#4926)
1 parent 32b5892 commit 9ec828f

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/pyodide/internal/_workers.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -220,14 +220,16 @@ def json(self, *args: Never, **kwargs: Never):
220220

221221
if pyodide_version == "0.26.0a2":
222222

223-
async def _pyfetch_patched(url: str, **kwargs: Any) -> "Response":
223+
async def _pyfetch_patched(
224+
request: "str | js.Request", **kwargs: Any
225+
) -> "Response":
224226
# This is copied from https://github.com/pyodide/pyodide/blob/d3f99e1d/src/py/pyodide/http.py
225227
custom_fetch = kwargs["fetcher"] if "fetcher" in kwargs else js.fetch
226228
kwargs["fetcher"] = None
227229
try:
228230
return Response(
229231
await custom_fetch(
230-
url, to_js(kwargs, dict_converter=Object.fromEntries)
232+
request, to_js(kwargs, dict_converter=Object.fromEntries)
231233
),
232234
)
233235
except JsException as e:
@@ -237,9 +239,11 @@ async def _pyfetch_patched(url: str, **kwargs: Any) -> "Response":
237239

238240

239241
async def fetch(
240-
resource: str,
242+
resource: "str | Request | js.Request",
241243
**other_options: Unpack[FetchKwargs],
242244
) -> "Response":
245+
if isinstance(resource, Request):
246+
resource = resource.js_object
243247
if "method" in other_options and isinstance(other_options["method"], HTTPMethod):
244248
other_options["method"] = other_options["method"].value
245249
resp = await _pyfetch_patched(resource, **other_options)

src/workerd/server/tests/python/sdk/worker.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ async def test(self):
170170
await request_unit_tests(js_env)
171171
await can_use_event_decorator(js_env)
172172
await response_unit_tests(js_env)
173+
await can_fetch_python_request()
173174

174175

175176
# TODO: Right now the `fetch` that's available on a binding is the JS fetch.
@@ -495,3 +496,11 @@ def __init__(self, x):
495496
)
496497
# TODO: it doesn't seem possible to access webSocket even in JS
497498
assert response_ws.status == 201
499+
500+
501+
async def can_fetch_python_request():
502+
def fetch_check(request, opts):
503+
assert isinstance(request, JsProxy)
504+
505+
async with _mock_fetch(fetch_check):
506+
await fetch(Request("https://example.com/redirect"))

0 commit comments

Comments
 (0)