diff --git a/CHANGELOG.md b/CHANGELOG.md index dbb61aa..7c5ec24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). ## [Unreleased] +### Fixed +- Ensure `requests.Session` is closed to prevent lingering TCP connections. ## [0.4.0] - 2025-01-20 ### Changed diff --git a/src/zapv2/__init__.py b/src/zapv2/__init__.py index 7541712..d61521a 100644 --- a/src/zapv2/__init__.py +++ b/src/zapv2/__init__.py @@ -137,12 +137,6 @@ def __init__(self, proxies=None, apikey=None, validate_status_code=False): # not very nice, but prevents warnings when accessing the ZAP API via https requests.packages.urllib3.disable_warnings(InsecureRequestWarning) - # Currently create a new session for each request to prevent request failing - # e.g. when polling the spider status - #self.session = requests.Session() - #if apikey is not None: - # self.session.headers['X-ZAP-API-Key'] = apikey - def urlopen(self, url, *args, **kwargs): """ Opens a url forcing the proxies to be used. @@ -170,11 +164,11 @@ def _request_api(self, url, query=None, method="GET", body=None): # In theory we should be able to reuse the session, # but there have been problems with that - self.session = requests.Session() - if self.__apikey is not None: - self.session.headers['X-ZAP-API-Key'] = self.__apikey + with requests.Session() as session: + if self.__apikey is not None: + session.headers['X-ZAP-API-Key'] = self.__apikey - response = self.session.request(method, url, params=query, data=body, proxies=self.__proxies, verify=False) + response = session.request(method, url, params=query, data=body, proxies=self.__proxies, verify=False) if (self.__validate_status_code and response.status_code >= 300 and response.status_code < 500): raise Exception("Non-successful status code returned from ZAP, which indicates a bad request: "