Skip to content

Commit

Permalink
Merge pull request #531 from stripe/brandur-thread-safe-clients
Browse files Browse the repository at this point in the history
Make `RequestsClient` thread-safe
  • Loading branch information
ob-stripe authored Jan 30, 2019
2 parents 3abca75 + 6cf50a6 commit f1b4260
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions stripe/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import email
import time
import random
import threading

import stripe
from stripe import error, util, six
Expand Down Expand Up @@ -101,6 +102,8 @@ def __init__(self, verify_ssl_certs=True, proxy=None):
)
self._proxy = proxy.copy() if proxy else None

self._thread_local = threading.local()

def request_with_retries(self, method, url, headers, post_data=None):
num_retries = 0

Expand Down Expand Up @@ -191,7 +194,7 @@ class RequestsClient(HTTPClient):
def __init__(self, timeout=80, session=None, **kwargs):
super(RequestsClient, self).__init__(**kwargs)
self._timeout = timeout
self._session = session or requests.Session()
self._thread_local.session = session or requests.Session()

def request(self, method, url, headers, post_data=None):
kwargs = {}
Expand All @@ -205,7 +208,7 @@ def request(self, method, url, headers, post_data=None):

try:
try:
result = self._session.request(
result = self._thread_local.session.request(
method,
url,
headers=headers,
Expand Down Expand Up @@ -285,8 +288,8 @@ def _handle_request_error(self, e):
raise error.APIConnectionError(msg, should_retry=should_retry)

def close(self):
if self._session is not None:
self._session.close()
if self._thread_local.session is not None:
self._thread_local.session.close()


class UrlFetchClient(HTTPClient):
Expand Down

0 comments on commit f1b4260

Please sign in to comment.