From 53d2d3b42b387ae18b8b843a27c9080cfbd5521e Mon Sep 17 00:00:00 2001 From: Leo Hemsted Date: Fri, 13 Oct 2023 18:12:12 +0100 Subject: [PATCH] re-use a single request session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This should unlock performance benefits by utilising HTTP keep-alive to reuse one TCP connection between many requests. Quoth the docs: [The Session object] across all requests [...] will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).[^1] [^1]: https://requests.readthedocs.io/en/latest/user/advanced/ --- CHANGELOG.md | 4 ++++ notifications_python_client/__init__.py | 2 +- notifications_python_client/base.py | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83413a0..0fee0dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 8.1.0 + +* Reuse the same `requests.session` between requests to increase performance through HTTP Keepalive + ## 8.0.1 * Some minor non-functional code reformatting. diff --git a/notifications_python_client/__init__.py b/notifications_python_client/__init__.py index ed9acf1..1091d43 100644 --- a/notifications_python_client/__init__.py +++ b/notifications_python_client/__init__.py @@ -7,7 +7,7 @@ # # -- http://semver.org/ -__version__ = "8.0.1" +__version__ = "8.1.0" from notifications_python_client.errors import ( # noqa REQUEST_ERROR_MESSAGE, diff --git a/notifications_python_client/base.py b/notifications_python_client/base.py index cbc4472..eed327d 100644 --- a/notifications_python_client/base.py +++ b/notifications_python_client/base.py @@ -32,6 +32,7 @@ def __init__(self, api_key, base_url="https://api.notifications.service.gov.uk", self.service_id = service_id self.api_key = api_key self.timeout = timeout + self.request_session = requests.Session() def put(self, url, data): return self.request("PUT", url, data=data) @@ -87,7 +88,7 @@ def _extended_json_encoder(self, obj): def _perform_request(self, method, url, kwargs): start_time = time.monotonic() try: - response = requests.request(method, url, **kwargs) + response = self.request_session.request(method, url, **kwargs) response.raise_for_status() return response except requests.RequestException as e: