0

I am confused about the use of the fetch() function in PyScript.

There seems to be two versions of that function:

  1. from the js module
  2. from the pyscript module

Only the first one seems to accept two arguments.

I want to include header informations like so:

request_options = {
  "method": "GET",
  "headers": { "charset": "UTF-8" }
}
        
url = "https://www.nanobooks23.de/material/schachclub2.json"
response = await fetch(
  "https://corsproxy.io/?" + url,
  request_options
)

This only works with the fetch() function from the js module.

Otherwise I'll receive an

TypeError: fetch() takes 1 positional argument but 2 were given

So, how can I include the headers when using the fetch() function from the pyscript module?

I am using PyScript version 2024.9.2

1 Answer 1

0

All the other except the url argument are keyword arguments, the url is the only positional argument.

Pass the arguments directly as body = body or use **{options}.

You cant pass them without keywords inside an object.

Sign up to request clarification or add additional context in comments.

6 Comments

When calling fetch like this response = await fetch( "corsproxy.io?" + url, method = "GET", headers = { "charset": "UTF-8" } ) I'll receive an "pyodide.ffi.JsException: TypeError: Failed to fetch" PS: I looks like another answer and my comment had been deleted?
I think that specifically with headers, you should wrap the object by headers = to_js({headers})
Now I'll get an "TypeError: Object of type JsProxy is not JSON serializable" error - I have to do some more research, but it works with fetch() from the js module
Im just going to the pyscript docs for giving answers, they are very comfortable and they are searchable so you can refer to them. Specifically on using headers - in the doc example, when using headers, they create an object of headers, wrap it with to_js, take all options including the "js" headers and put in another object, arranged with the names "headers=jsheaders" etc. and wrap all the options object by another to_js, and then give it to fetch as options=options
It just don't work for me when using something simple like headers={ "Content-Type": "application/json"}. It always leads to an pyodide.ffi.JsException: TypeError: NetworkError when attempting to fetch resource. When leaving out headers and just providing url and method with the fetch() function from PyScript it works. I could not find anything in the PyScript docu.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.