httpx conversion

This commit is contained in:
2026-03-18 19:32:16 -04:00
parent 42330ec186
commit 1b5a036061
4 changed files with 9 additions and 13 deletions

View File

@@ -34,7 +34,6 @@
pytest-mock pytest-mock
pytest-xdist pytest-xdist
python-multipart python-multipart
requests
ruff ruff
scalene scalene
sqlalchemy sqlalchemy
@@ -43,7 +42,6 @@
textual textual
tinytuya tinytuya
typer typer
types-requests
websockets websockets
] ]
); );

View File

@@ -18,7 +18,6 @@ dependencies = [
"psycopg[binary]", "psycopg[binary]",
"pydantic", "pydantic",
"pyyaml", "pyyaml",
"requests",
"sqlalchemy", "sqlalchemy",
"typer", "typer",
"websockets", "websockets",
@@ -37,7 +36,6 @@ dev = [
"pytest-xdist", "pytest-xdist",
"pytest", "pytest",
"ruff", "ruff",
"types-requests",
] ]
[tool.ruff] [tool.ruff]

View File

@@ -5,7 +5,7 @@ from __future__ import annotations
import logging import logging
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
import requests import httpx
if TYPE_CHECKING: if TYPE_CHECKING:
from python.signal_bot.models import SignalMessage from python.signal_bot.models import SignalMessage
@@ -18,7 +18,7 @@ def _get_entity_state(ha_url: str, ha_token: str, entity_id: str) -> dict[str, A
"""Fetch an entity's state from Home Assistant.""" """Fetch an entity's state from Home Assistant."""
entity_url = f"{ha_url}/api/states/{entity_id}" entity_url = f"{ha_url}/api/states/{entity_id}"
logger.debug(f"Fetching {entity_url=}") logger.debug(f"Fetching {entity_url=}")
response = requests.get( response = httpx.get(
entity_url, entity_url,
headers={"Authorization": f"Bearer {ha_token}"}, headers={"Authorization": f"Bearer {ha_token}"},
timeout=30, timeout=30,
@@ -48,7 +48,7 @@ def handle_location_request(
try: try:
lat_payload = _get_entity_state(ha_url, ha_token, "sensor.van_last_known_latitude") lat_payload = _get_entity_state(ha_url, ha_token, "sensor.van_last_known_latitude")
lon_payload = _get_entity_state(ha_url, ha_token, "sensor.van_last_known_longitude") lon_payload = _get_entity_state(ha_url, ha_token, "sensor.van_last_known_longitude")
except requests.RequestException: except httpx.HTTPError:
logger.exception("Couldn't fetch van location from Home Assistant right now.") logger.exception("Couldn't fetch van location from Home Assistant right now.")
logger.debug(f"{ha_url=} {lat_payload=} {lon_payload=}") logger.debug(f"{ha_url=} {lat_payload=} {lon_payload=}")
signal.reply(message, "Couldn't fetch van location from Home Assistant right now.") signal.reply(message, "Couldn't fetch van location from Home Assistant right now.")

View File

@@ -4,7 +4,7 @@ import logging
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Annotated, Any from typing import Annotated, Any
import requests import httpx
import typer import typer
from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.blocking import BlockingScheduler
from tenacity import before_sleep_log, retry, stop_after_attempt, wait_fixed from tenacity import before_sleep_log, retry, stop_after_attempt, wait_fixed
@@ -37,7 +37,7 @@ logger = logging.getLogger(__name__)
) )
def get_ha_state(url: str, token: str, entity_id: str) -> float: def get_ha_state(url: str, token: str, entity_id: str) -> float:
"""Get numeric state from Home Asasistant entity.""" """Get numeric state from Home Asasistant entity."""
response = requests.get( response = httpx.get(
f"{url}/api/states/{entity_id}", f"{url}/api/states/{entity_id}",
headers={"Authorization": f"Bearer {token}"}, headers={"Authorization": f"Bearer {token}"},
timeout=30, timeout=30,
@@ -102,7 +102,7 @@ def parse_hourly_forecast(data: dict[str, dict[str, Any]]) -> list[HourlyForecas
def fetch_weather(api_key: str, lat: float, lon: float) -> Weather: def fetch_weather(api_key: str, lat: float, lon: float) -> Weather:
"""Fetch weather from Pirate Weather API.""" """Fetch weather from Pirate Weather API."""
url = f"https://api.pirateweather.net/forecast/{api_key}/{lat},{lon}" url = f"https://api.pirateweather.net/forecast/{api_key}/{lat},{lon}"
response = requests.get(url, params={"units": "us"}, timeout=30) response = httpx.get(url, params={"units": "us"}, timeout=30)
response.raise_for_status() response.raise_for_status()
data = response.json() data = response.json()
@@ -204,7 +204,7 @@ def post_to_ha(url: str, token: str, weather: Weather) -> None:
for entity_id, data in sensors.items(): for entity_id, data in sensors.items():
if data["state"] is not None: if data["state"] is not None:
response = requests.post(f"{url}/api/states/{entity_id}", headers=headers, json=data, timeout=30) response = httpx.post(f"{url}/api/states/{entity_id}", headers=headers, json=data, timeout=30)
response.raise_for_status() response.raise_for_status()
# Post daily forecast as JSON attribute sensor # Post daily forecast as JSON attribute sensor
@@ -219,7 +219,7 @@ def post_to_ha(url: str, token: str, weather: Weather) -> None:
for daily_forecast in weather.daily_forecasts for daily_forecast in weather.daily_forecasts
] ]
response = requests.post( response = httpx.post(
f"{url}/api/states/sensor.van_weather_forecast_daily", f"{url}/api/states/sensor.van_weather_forecast_daily",
headers=headers, headers=headers,
json={"state": len(daily_forecast), "attributes": {"forecast": daily_forecast}}, json={"state": len(daily_forecast), "attributes": {"forecast": daily_forecast}},
@@ -238,7 +238,7 @@ def post_to_ha(url: str, token: str, weather: Weather) -> None:
for hourly_forecast in weather.hourly_forecasts for hourly_forecast in weather.hourly_forecasts
] ]
response = requests.post( response = httpx.post(
f"{url}/api/states/sensor.van_weather_forecast_hourly", f"{url}/api/states/sensor.van_weather_forecast_hourly",
headers=headers, headers=headers,
json={"state": len(hourly_forecast), "attributes": {"forecast": hourly_forecast}}, json={"state": len(hourly_forecast), "attributes": {"forecast": hourly_forecast}},