How Can I Use The Post Api Using Pyodide
In pyodide, it is not support the requests module so to fetch the data from api we used open_url and how can we use the api for post the Data using pyodide
Solution 1:
The requests module is currently not supported in pyodide because it relies on sockets which are not implemented in the WebAssembly browser VM.
You can however, make POST calls using Web APIs in pyodide. Below is an example using XMLHttpRequest
from js import XMLHttpRequest, Blob
import json
data = {"a": 1}
req = XMLHttpRequest.new()
req.open("POST", "https://httpbin.org/anything", False)
blob = Blob.new([json.dumps(data)], {type : 'application/json'})
req.send(blob)
str(req.response)
In the future it's possible that some of the classical HTTP client modules might be patched to use Web APIs in pyodide (cf pyodide#140).
Solution 2:
You can also use JS Fetch API direct form Python code. To do this, you first have to import window
object from js
module. Here is a live demo:
let python_code = `
from js import window
def fetch():
window.fetch('http://karay.me/truepyxel/test.json').then(lambda resp: resp.json()).then(lambda jsoh: show_result(jsoh))
def show_result(data):
div = window.document.createElement('div')
#insert into body as a first child
window.document.body.prepend(div)
div.innerHTML=window.JSON.stringify(data)
`// init environment
languagePluginLoader
// then run Python code
.then(() => pyodide.runPythonAsync(python_code));
<!DOCTYPE html><html><head><scriptsrc="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script></head><body><buttononclick='pyodide.globals.fetch()'>Fetch</button></body></html>
Post a Comment for "How Can I Use The Post Api Using Pyodide"