Skip to content

Commit beeda52

Browse files
committed
Ensure TCP connections are properly closed
Use a context-managed `requests.Session` to guarantee that the session and its underlying TCP connections are properly closed. This prevents `ResourceWarning` messages being written to stderr. Signed-off-by: Moritz Duchêne <[email protected]>
1 parent ba0537d commit beeda52

File tree

2 files changed

+6
-10
lines changed

2 files changed

+6
-10
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
55

66
## [Unreleased]
7+
### Fixed
8+
- Ensure `requests.Session` is closed to prevent lingering TCP connections.
79

810
## [0.4.0] - 2025-01-20
911
### Changed

src/zapv2/__init__.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,6 @@ def __init__(self, proxies=None, apikey=None, validate_status_code=False):
137137
# not very nice, but prevents warnings when accessing the ZAP API via https
138138
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
139139

140-
# Currently create a new session for each request to prevent request failing
141-
# e.g. when polling the spider status
142-
#self.session = requests.Session()
143-
#if apikey is not None:
144-
# self.session.headers['X-ZAP-API-Key'] = apikey
145-
146140
def urlopen(self, url, *args, **kwargs):
147141
"""
148142
Opens a url forcing the proxies to be used.
@@ -170,11 +164,11 @@ def _request_api(self, url, query=None, method="GET", body=None):
170164

171165
# In theory we should be able to reuse the session,
172166
# but there have been problems with that
173-
self.session = requests.Session()
174-
if self.__apikey is not None:
175-
self.session.headers['X-ZAP-API-Key'] = self.__apikey
167+
with requests.Session() as session:
168+
if self.__apikey is not None:
169+
session.headers['X-ZAP-API-Key'] = self.__apikey
176170

177-
response = self.session.request(method, url, params=query, data=body, proxies=self.__proxies, verify=False)
171+
response = session.request(method, url, params=query, data=body, proxies=self.__proxies, verify=False)
178172

179173
if (self.__validate_status_code and response.status_code >= 300 and response.status_code < 500):
180174
raise Exception("Non-successful status code returned from ZAP, which indicates a bad request: "

0 commit comments

Comments
 (0)