refactor(utils): replace requests with urllib and improve error handling
Replace external `requests` calls with `urllib` to eliminate third‑party dependency, add robust timeout handling, and improve error reporting. This also standardises URL fetching across the module and updates the process name configuration. Enhancements: - Added default request timeout fallback and ensured proper cleanup of response objects - Enriched exception messages for better debugging Bug Fixes: - Fixed potential timeout‑related crashes in `CurrencyCache` and `Conversion` - Corrected process name setting via `set_process_name` in the entry point
This commit is contained in:
2 files changed
+25
-13
No files matched your search
+18
-11
@@ -3,7 +3,9 @@ import time
|
|||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from typing import Dict, Optional, Tuple
|
from typing import Dict, Optional, Tuple
|
||||||
|
|
||||||
import requests
|
import json
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
|
||||||
|
|
||||||
class CurrencyCache:
|
class CurrencyCache:
|
||||||
@@ -79,11 +81,12 @@ class CurrencyCache:
|
|||||||
"""Fetch exchange rates in background thread."""
|
"""Fetch exchange rates in background thread."""
|
||||||
try:
|
try:
|
||||||
url = f"https://www.floatrates.com/daily/{from_code}.json"
|
url = f"https://www.floatrates.com/daily/{from_code}.json"
|
||||||
response = requests.get(url, timeout=self._request_timeout)
|
if self._request_timeout is None:
|
||||||
|
self._request_timeout = 5
|
||||||
if response.status_code == 200:
|
with urllib.request.urlopen(url, timeout=self._request_timeout) as response:
|
||||||
rates_data = response.json()
|
if response.getcode() == 200:
|
||||||
current_time = time.time()
|
rates_data = json.loads(response.read().decode())
|
||||||
|
current_time = time.time()
|
||||||
|
|
||||||
with self._cache_lock:
|
with self._cache_lock:
|
||||||
self._cache[from_code] = {
|
self._cache[from_code] = {
|
||||||
@@ -523,11 +526,15 @@ class Conversion:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
url = f"https://www.floatrates.com/daily/{from_lower}.json"
|
url = f"https://www.floatrates.com/daily/{from_lower}.json"
|
||||||
resp = requests.get(url, timeout=5)
|
try:
|
||||||
if resp.status_code != 200:
|
with urllib.request.urlopen(url, timeout=5) as resp:
|
||||||
raise ValueError(f"Error getting data from floatrates for {from_code}")
|
if resp.getcode() != 200:
|
||||||
|
raise ValueError(
|
||||||
data = resp.json()
|
f"Error getting data from floatrates for {from_code}"
|
||||||
|
)
|
||||||
|
data = json.loads(resp.read().decode())
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(f"Error getting data from floatrates for {from_code}: {e}")
|
||||||
if to_lower not in data:
|
if to_lower not in data:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Target currency '{to_code}' not found in floatrates response for '{
|
f"Target currency '{to_code}' not found in floatrates response for '{
|
||||||
|
|||||||
+7
-2
@@ -6,10 +6,15 @@ import os
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# Add the project root to sys.path to allow absolute imports from 'utils'
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
from signal import SIGINT, SIGTERM, signal
|
from signal import SIGINT, SIGTERM, signal
|
||||||
from threading import Event, Timer
|
from threading import Event, Timer
|
||||||
|
|
||||||
import setproctitle
|
from utils.functions import set_process_name
|
||||||
from pywayland.client.display import Display
|
from pywayland.client.display import Display
|
||||||
from pywayland.protocol.idle_inhibit_unstable_v1.zwp_idle_inhibit_manager_v1 import (
|
from pywayland.protocol.idle_inhibit_unstable_v1.zwp_idle_inhibit_manager_v1 import (
|
||||||
ZwpIdleInhibitManagerV1,
|
ZwpIdleInhibitManagerV1,
|
||||||
@@ -182,5 +187,5 @@ def main() -> None:
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
setproctitle.setproctitle("modus-inhibit")
|
set_process_name("modus-inhibit")
|
||||||
main()
|
main()
|
||||||
Reference in new issue
Block a user