I am running a script with pyscript and I believe the issue is that it needs the “requests” library based on the error:
Exception in <file.example2.final_test_2> line 18: response = requests.get(url) ^ NameError: name 'requests.get' is not defined During handling of the above exception, another exception occurred: Exception in <file.example2.final_test_2> line 26: raise ValueError(f"Error: {str(e)} - Unable to fetch webpage") ^ ValueError: Error: name 'requests.get' is not defined - Unable to fetch webpage
I am unsure how to import or add this library. Based on what I read on Reference — hacs-pyscript 1.5.0 documentation it says
Pyscript code can be put into modules or packages and stored in the
<config>/pyscript/modules
folder.
So what does that really mean? If I go to requests · PyPI and download the libary. I get a file called requests-2.31.0-py3-none-any.whl. What do I do with this? Do I just drop that file in? I’m lost.
code:
@service
def final_test_2(action=None, id=None):
#import json
import re
import requests
# Define the variables for node and MAC address
node = "wtn"
mac_address = "hidden_for_privacy"
# Construct the URL with the node and MAC address variables
PTD_BANDWIDTH_GRAPH_URL = f"https://www.engr.ptd.net/login/cableutil/cableutil_graph_gen.cgi?type=standard&node={node}&partner=SECV&source=OpenVault&address={mac_address}&keepnode=&start=&end="
PATTERN = r"<h4>This Month[\s\S]+?Total Upstream:[\s\S]+?GB \(<font style='color: red'>(?P<upload>\d+)[\s\S]+?Total Downstream: [\s\S]+?GB \(<font style='color: green'>(?P<download>\d+)"
def fetch_webpage(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
#return f"Error: {response.status_code} - Unable to fetch webpage"
raise ValueError(f"Error: {response.status_code} - Unable to fetch webpage")
except Exception as e:
#return f"Error: {str(e)} - Unable to fetch webpage"
raise ValueError(f"Error: {str(e)} - Unable to fetch webpage")
html = fetch_webpage(PTD_BANDWIDTH_GRAPH_URL) # fetch page
matches = re.finditer(PATTERN, html) # run regex
upload_data = None
download_data = None
total_data = None
for match in matches:
upload_data = round(int(match.group('upload')) / 1024 / 1024 / 1024, 2) # convert bytes to GB
download_data = round(int(match.group('download')) / 1024 / 1024 / 1024, 2) # convert bytes to GB
total_data = round((upload_data + download_data),2)
service.call("input_number", "set_value", entity_id="input_number.ptd_upload_data", value=upload_data)
service.call("input_number", "set_value", entity_id="input_number.ptd_download_data", value=download_data)
service.call("input_number", "set_value", entity_id="input_number.ptd_total_data", value=total_data)