1515"""Shared implementation of connections to API servers."""
1616
1717import json
18+ import threading
19+
20+ import httplib2
1821from pkg_resources import get_distribution
1922import six
2023from six .moves .urllib .parse import urlencode # pylint: disable=F0401
2124
22- import httplib2
23-
2425from gcloud .exceptions import make_exception
2526
2627
@@ -55,6 +56,8 @@ class Connection(object):
5556 object will also need to be able to add a bearer token to API
5657 requests and handle token refresh on 401 errors.
5758
59+ A custom ``http`` object will also need to ensure its own thread safety.
60+
5861 :type credentials: :class:`oauth2client.client.OAuth2Credentials` or
5962 :class:`NoneType`
6063 :param credentials: The OAuth2 Credentials to use for this connection.
@@ -73,6 +76,7 @@ class Connection(object):
7376 """
7477
7578 def __init__ (self , credentials = None , http = None ):
79+ self ._local = threading .local ()
7680 self ._http = http
7781 self ._credentials = self ._create_scoped_credentials (
7882 credentials , self .SCOPE )
@@ -91,14 +95,24 @@ def credentials(self):
9195 def http (self ):
9296 """A getter for the HTTP transport used in talking to the API.
9397
94- :rtype: :class:`httplib2.Http`
95- :returns: A Http object used to transport data.
98+ This will return a thread-local :class:`httplib2.Http` instance unless
99+ a custom transport has been provided to the :class:`Connection`
100+ constructor.
101+
102+ :rtype: :class:`httplib2.Http` or the custom HTTP transport specifed
103+ to the connection constructor.
104+ :returns: An ``Http`` object used to transport data.
96105 """
97- if self ._http is None :
98- self ._http = httplib2 .Http ()
106+ if self ._http is not None :
107+ return self ._http
108+
109+ if not hasattr (self ._local , 'http' ):
110+ self ._local .http = httplib2 .Http ()
99111 if self ._credentials :
100- self ._http = self ._credentials .authorize (self ._http )
101- return self ._http
112+ self ._local .http = self ._credentials .authorize (
113+ self ._local .http )
114+
115+ return self ._local .http
102116
103117 @staticmethod
104118 def _create_scoped_credentials (credentials , scope ):
0 commit comments