Skip to content

Commit

Permalink
re-use a single request session
Browse files Browse the repository at this point in the history
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/
  • Loading branch information
leohemsted committed Oct 17, 2023
1 parent fdaeea9 commit 53d2d3b
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion notifications_python_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion notifications_python_client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 53d2d3b

Please sign in to comment.