I have a PyScript running on the home.html page of a website, and within the script I'd like to read some information from a file stored in same directory as the home.html page but I always get error "Host is unreachable". I expect to be able to read information from a file stored in same directory as my home.html page containing the script.
I am trying the following:
url='<my file full URL here>'
req = urllib.request.Request(url=url)
response = urllib.request.urlopen(req,timeout=120)
data=response.read().decode('utf-8')
CodePudding user response:
PyScript doesn't play well (actually, doesn't play at all) with most existing Python libraries that handle HTTP requests (requests, httpx, urllib). Take a look at the PyScript documentation on HTTP requests here for guidance. It's a great walk-through on making HTTP requests in PyScript using pyfetch
, a Python wrapper of the JavaScript fetch
api.
One quick warning about the documentation. Like PyScript itself, the documentation is a work in progress. In the link above, there's a reference to the py-env
tag. That has been deprecated and it doesn't look like they've updated that part of the documentation. The functions of the py-env
tag have been subsumed in the py-config
tag. More on that here.
CodePudding user response:
Here is what I am doing (NB: this is a pure draft, also the URL is a dummy one):
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<body bgcolor="#000000">
<py-config type="toml">
packages = ["numpy"]
paths = ["./request.py"]
</py-config>
<p style="color:green; font-family:'Courier New'">
<strong>
<py-script>
import io
import asyncio
import json
import sys
from request import request
baseurl = "https://jsonplaceholder.typicode.com/"
headers = {"Content-type": "application/json"}
response = await request(baseurl "posts/2", method="GET", headers=headers)
print(f"GET request=> status:{response.status}, json:{await response.json()}")
</py-script>
</strong>
</p>
</body>
</html>
When loading the page, I get this error: "OSError: Request for ./request.py failed with status 500: Internal Server Error". Full message below:
"PyScript encountered an error while loading from file: Traceback (most recent call last): File "/lib/python3.10/asyncio/futures.py", line 201, in result raise self._exception File "/lib/python3.10/asyncio/tasks.py", line 232, in __step result = coro.send(None) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 506, in eval_code_async await CodeRunner( File "/lib/python3.10/site-packages/_pyodide/_base.py", line 359, in run_async await coroutine File "", line 10, in File "/lib/python3.10/site-packages/pyodide/http.py", line 149, in bytes self._raise_if_failed() File "/lib/python3.10/site-packages/pyodide/http.py", line 107, in _raise_if_failed raise OSError( OSError: Request for ./request.py failed with status 500: Internal Server Error"