Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure requests.Session is not shared between threads #77

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions customerio/client_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from __future__ import division
from datetime import datetime, timezone
import math
import threading

from requests import Session
from requests.adapters import HTTPAdapter
Expand All @@ -18,14 +19,21 @@ class ClientBase(object):
def __init__(self, retries=3, timeout=10, backoff_factor=0.02):
self.timeout = timeout
self.retries = retries
self.backoff_factor = backoff_factor

self.http = Session()
self.http.headers['User-Agent'] = "Customer.io Python Client/{version}".format(version=ClientVersion)
self.thread_local = threading.local()

# Retry request a number of times before raising an exception
# also define backoff_factor to delay each retry
self.http.mount('https://', HTTPAdapter(max_retries=Retry(
total=retries, backoff_factor=backoff_factor)))
@property
def http(self):
if getattr(self.thread_local, "http", None) is None:
self.thread_local.http = Session()
self.thread_local.http.headers['User-Agent'] = "Customer.io Python Client/{version}".format(version=ClientVersion)

# Retry request a number of times before raising an exception
# also define backoff_factor to delay each retry
self.thread_local.http.mount('https://', HTTPAdapter(max_retries=Retry(
total=self.retries, backoff_factor=self.backoff_factor)))
return self.thread_local.http

def send_request(self, method, url, data):
'''Dispatches the request and returns a response'''
Expand Down