From 4f01f7187d676a0d689848afbabcc8daea4cf061 Mon Sep 17 00:00:00 2001 From: Niko Date: Fri, 7 Mar 2025 20:02:43 +0100 Subject: [PATCH] Avoid garbage collection for requests.Session (#1189) * workaround for garbage collection * add missing import * linting issues (wrong import order) * fix imports --- CHANGELOG.md | 1 + spotipy/client.py | 9 +++------ spotipy/oauth2.py | 5 +++-- spotipy/util.py | 4 ++++ 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3878654..c751afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ Add your changes below. - Fixed scripts in examples directory that didn't run correctly - Updated documentation for `Client.current_user_top_artists` to indicate maximum number of artists limit - Set auth cache file permissions to `600`: https://github.com/spotipy-dev/spotipy/security/advisories/GHSA-pwhh-q4h6-w599 +- Fixed `__del__` methods by preventing garbage collection for `requests.Session` ### Changed diff --git a/spotipy/client.py b/spotipy/client.py index b622b14..03825a8 100644 --- a/spotipy/client.py +++ b/spotipy/client.py @@ -11,7 +11,7 @@ from collections import defaultdict import requests from spotipy.exceptions import SpotifyException -from spotipy.util import Retry +from spotipy.util import REQUESTS_SESSION, Retry logger = logging.getLogger(__name__) @@ -211,11 +211,8 @@ class Spotify: def __del__(self): """Make sure the connection (pool) gets closed""" - try: - if isinstance(self._session, requests.Session): - self._session.close() - except AttributeError: - pass + if getattr(self, "_session", None) and isinstance(self._session, REQUESTS_SESSION): + self._session.close() def _build_session(self): self._session = requests.Session() diff --git a/spotipy/oauth2.py b/spotipy/oauth2.py index e949f84..371dd16 100644 --- a/spotipy/oauth2.py +++ b/spotipy/oauth2.py @@ -21,7 +21,8 @@ import requests from spotipy.cache_handler import CacheFileHandler, CacheHandler from spotipy.exceptions import SpotifyOauthError, SpotifyStateError -from spotipy.util import CLIENT_CREDS_ENV_VARS, get_host_port, normalize_scope +from spotipy.util import (CLIENT_CREDS_ENV_VARS, REQUESTS_SESSION, + get_host_port, normalize_scope) logger = logging.getLogger(__name__) @@ -122,7 +123,7 @@ class SpotifyAuthBase: def __del__(self): """Make sure the connection (pool) gets closed""" - if isinstance(self._session, requests.Session): + if getattr(self, "_session", None) and isinstance(self._session, REQUESTS_SESSION): self._session.close() diff --git a/spotipy/util.py b/spotipy/util.py index 4aeef09..145f08e 100644 --- a/spotipy/util.py +++ b/spotipy/util.py @@ -9,6 +9,7 @@ import os import warnings from types import TracebackType +import requests import urllib3 import spotipy @@ -22,6 +23,9 @@ CLIENT_CREDS_ENV_VARS = { "redirect_uri": "SPOTIPY_REDIRECT_URI", } +# workaround for garbage collection +REQUESTS_SESSION = requests.Session + def prompt_for_user_token( username=None,