The "requests" module

Anyone else facing this: ModuleNotFoundError: No module named ‘requests’ ?
I’m building an webpage that shows informations about postal code here in Brazil. But it uses an API. Cant we use this library yet?

2 Likes

requests would be impossible to implement in a browser given the way WASM and requests currently work. I believe you must use pyfetch.

1 Like

I found this workaround via a requests shim that uses XMLHttpRequest under the hood:
https://bartbroere.eu/2022/04/25/pyodide-requests-binary-works-update/

I’m also having this problem. I made some progress…

<html>
  <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
  <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  <py-env>
    - requests
  </py-env>
  <body>
    Hello, world!
    <div id="outputDiv" class="font-mono"></div>
    <py-script>
import requests
r = requests.get('https://myexternalip.com/raw')
pyscript.write("outputDiv", r.text)
    </py-script>
  </body>
</html>
  • Anything with http:// produces a “Protocol not available” error.
  • Anything with https:// produces a “Can’t connect to HTTPS URL because the SSL module is not available.” error.

I tried loading/importing PyOpenSSL in hopes to fix the https error, but it can’t install cryptography via micropip because it doesn’t have a pure python 3 wheel. It seems that Pyodide has added cryptography, libssl, and _ssl packages, so I’m unsure why there’s an error: Add cryptography, openssl, and _ssl packages by hoodmane · Pull Request #2263 · pyodide/pyodide · GitHub

You can use XMLHttpRequest as @jim.kring mentioned above, but this isn’t ideal imo

<html>
  <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
  <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  <body>
    Hello, world!
    <div id="outputDiv" class="font-mono"></div>
    <py-script>
from js import XMLHttpRequest

req = XMLHttpRequest.new()
req.open("GET", "https://myexternalip.com/raw", False)
req.send(None)

pyscript.write("outputDiv", str(req.response))
    </py-script>
  </body>
</html>

Keep in mind that if you use XMLHttpRequest in this manner that you need to make a web request that has some actual raw output / json. If not it’s going to pop a CORS error, you can disable this tho in your browser if you want.