replace requests with httpx

This commit is contained in:
Logan Cusano
2025-06-07 23:24:02 -04:00
parent 6b2aee72e0
commit 4a93cf5c71

View File

@@ -1,7 +1,7 @@
import socket import socket
import requests import httpx
def generate_node_nickname(): def generate_unit_registration_id():
""" """
Generates a temporary unit registration ID in the format: Generates a temporary unit registration ID in the format:
"Node-{last octet of local IP}-{last octet of public IP}". "Node-{last octet of local IP}-{last octet of public IP}".
@@ -21,23 +21,26 @@ def generate_node_nickname():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Connect to an external host (Google's DNS) to get the local IP # Connect to an external host (Google's DNS) to get the local IP
# This doesn't send any data, just establishes a connection for getsockname() # This doesn't send any data, just establishes a connection for getsockname()
s.connect(("1.1.1.1", 80)) s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0] local_ip = s.getsockname()[0]
s.close() s.close()
local_ip_octet = local_ip.split('.')[-1] local_ip_octet = local_ip.split('.')[-1]
except Exception as e: except Exception as e:
print(f"Warning: Could not determine local IP address. Error: {e}") print(f"Warning: Could not determine local IP address. Error: {e}")
# Get the last octet of the public IP address using an external service # Get the last octet of the public IP address using an external service with httpx
try: try:
# Use ipify.org to get the public IP (a widely used, simple service) # Use ipify.org to get the public IP (a widely used, simple service)
response = requests.get('https://api.ipify.org?format=json') # httpx.get() is synchronous by default
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx) response = httpx.get('https://api.ipify.org?format=json')
response.raise_for_status() # Raise an HTTPStatusError for bad responses (4xx or 5xx)
public_ip = response.json()['ip'] public_ip = response.json()['ip']
public_ip_octet = public_ip.split('.')[-1] public_ip_octet = public_ip.split('.')[-1]
except requests.exceptions.RequestException as e: except httpx.RequestError as e:
print(f"Warning: Could not determine public IP address. Error: {e}") print(f"Warning: Could not determine public IP address (network error with httpx). Error: {e}")
except httpx.HTTPStatusError as e:
print(f"Warning: Could not determine public IP address (HTTP status error with httpx). Error: {e}")
except ValueError as e: except ValueError as e:
print(f"Warning: Could not parse public IP response. Error: {e}") print(f"Warning: Could not parse public IP response. Error: {e}")
return f"Node-{local_ip_octet}-{public_ip_octet}" return f"Node-{local_ip_octet}-{public_ip_octet}"