Braintree provides a Python library for interacting with their API.
However, with logging enabled, it can be seen that every API call negotiates a new SSL connection.
braintree.Customer.create({'first_name': 'Alice'})
braintree.Customer.create({'first_name': 'Bob'})
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): api.sandbox.braintreegateway.com
DEBUG:requests.packages.urllib3.connectionpool:"POST /merchants/hx4tr43ms83q8x9g/customers HTTP/1.1" 201 None
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): api.sandbox.braintreegateway.com
DEBUG:requests.packages.urllib3.connectionpool:"POST /merchants/hx4tr43ms83q8x9g/customers HTTP/1.1" 201 None
With lots of calls, this adds up to a lot of wasted resources - time in particular.
Is there any way to configure braintree to reuse/pool connections, which the underlying requests module should support?
It's not officially supported as it overrides a private method, but you can provide an alternate HTTP implementation. This one will send all API requests through a session.
class SessionHttp(braintree.util.http.Http):
session = requests.Session()
def __init__(self, config, environment=None):
super(SessionHttp, self).__init__(config, environment)
def _Http__request_function(self, method):
if method == "GET":
return SessionHttp.session.get
elif method == "POST":
return SessionHttp.session.post
elif method == "PUT":
return SessionHttp.session.put
elif method == "DELETE":
return SessionHttp.session.delete
braintree.Configuration.configure(
# ...
http_strategy=SessionHttp
)
braintree.Customer.create({'first_name': 'Alice'})
braintree.Customer.create({'first_name': 'Bob'})
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): api.sandbox.braintreegateway.com
DEBUG:requests.packages.urllib3.connectionpool:"POST /merchants/hx4tr43ms83q8x9g/customers HTTP/1.1" 201 None
DEBUG:requests.packages.urllib3.connectionpool:"POST /merchants/hx4tr43ms83q8x9g/customers HTTP/1.1" 201 None