Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Last active May 8, 2022 11:49
Show Gist options
  • Save amitsaha/61bb8aeaa81daebc5bb6148158bdb3c6 to your computer and use it in GitHub Desktop.
Save amitsaha/61bb8aeaa81daebc5bb6148158bdb3c6 to your computer and use it in GitHub Desktop.
Pyowm + Pyodide - patching "requests" module
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js"></script>
</head>
<body>
Pyodide test page <br>
Open your browser console to see Pyodide output
<script type="text/javascript">
async function main(){
let pyodide = await loadPyodide();
console.log(pyodide.runPython(`
import sys
sys.version
`));
console.log(pyodide.runPython("print(1 + 2)"));
await pyodide.loadPackage("micropip");
await pyodide.loadPackage("setuptools");
await pyodide.loadPackage("ssl");
pyodide.runPythonAsync(`
import micropip
import pyodide
import json
from unittest import mock
await micropip.install('pyowm')
from pyowm import OWM
import pyowm.commons.http_client
class MyResponse:
def __init__(self, status_code, message, json_body):
self.status_code = status_code
self.text = message
self.json_body = json_body
def json(self):
return self.json_body
class PyodideRequests:
def __init__(self):
pass
def get(self, uri, **kwargs):
print("URI", uri)
print("Got kwargs", kwargs)
query_params = []
for k, v in kwargs["params"].items():
query_params.append(k + "=" + v)
query_string = "&".join(query_params)
print(query_string)
response = pyodide.open_url(uri + "?" + query_string)
json_response = response.getvalue()
d = json.loads(json_response)
print(json_response)
return MyResponse(int(d["cod"]), d["message"], json.loads(json_response))
pyodide_requests = PyodideRequests()
with mock.patch('pyowm.commons.http_client.requests', pyodide_requests):
# Get a token from https://home.openweathermap.org/users/sign_up
owm = OWM('79cf83986bd2ba51194501fd711b0d71')
mgr = owm.weather_manager()
three_h_forecast = mgr.forecast_at_place('new york, us', '3h').forecast
print(len(three_h_forecast))
`);
}
main();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment