mirror of
https://github.com/home-assistant/core
synced 2024-09-03 08:14:07 +02:00
Use a requests Session for rest sensors (#32463)
This avoids the ssl setup overhead for each request
This commit is contained in:
parent
b27c46750c
commit
7f91501a36
@ -5,6 +5,7 @@ from xml.parsers.expat import ExpatError
|
|||||||
|
|
||||||
from jsonpath import jsonpath
|
from jsonpath import jsonpath
|
||||||
import requests
|
import requests
|
||||||
|
from requests import Session
|
||||||
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
|
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
import xmltodict
|
import xmltodict
|
||||||
@ -271,9 +272,14 @@ class RestData:
|
|||||||
self._request_data = data
|
self._request_data = data
|
||||||
self._verify_ssl = verify_ssl
|
self._verify_ssl = verify_ssl
|
||||||
self._timeout = timeout
|
self._timeout = timeout
|
||||||
|
self._http_session = Session()
|
||||||
self.data = None
|
self.data = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
"""Destroy the http session on destroy."""
|
||||||
|
self._http_session.close()
|
||||||
|
|
||||||
def set_url(self, url):
|
def set_url(self, url):
|
||||||
"""Set url."""
|
"""Set url."""
|
||||||
self._resource = url
|
self._resource = url
|
||||||
@ -282,7 +288,7 @@ class RestData:
|
|||||||
"""Get the latest data from REST service with provided method."""
|
"""Get the latest data from REST service with provided method."""
|
||||||
_LOGGER.debug("Updating from %s", self._resource)
|
_LOGGER.debug("Updating from %s", self._resource)
|
||||||
try:
|
try:
|
||||||
response = requests.request(
|
response = self._http_session.request(
|
||||||
self._method,
|
self._method,
|
||||||
self._resource,
|
self._resource,
|
||||||
headers=self._headers,
|
headers=self._headers,
|
||||||
|
@ -672,7 +672,7 @@ class TestRestData(unittest.TestCase):
|
|||||||
self.rest.update()
|
self.rest.update()
|
||||||
assert "test data" == self.rest.data
|
assert "test data" == self.rest.data
|
||||||
|
|
||||||
@patch("requests.request", side_effect=RequestException)
|
@patch("requests.Session.request", side_effect=RequestException)
|
||||||
def test_update_request_exception(self, mock_req):
|
def test_update_request_exception(self, mock_req):
|
||||||
"""Test update when a request exception occurs."""
|
"""Test update when a request exception occurs."""
|
||||||
self.rest.update()
|
self.rest.update()
|
||||||
|
Loading…
Reference in New Issue
Block a user