Merge branch 'master' into 4823-python-sdk-writable-collection-api
[arvados.git] / sdk / python / arvados / safeapi.py
1 import threading
2 import api
3 import keep
4 import config
5 import copy
6
7 class SafeApi(object):
8     """Threadsafe wrapper for API object.  This stores and returns a different api
9     object per thread, because httplib2 which underlies apiclient is not
10     threadsafe.
11     """
12
13     def __init__(self, apiconfig=None, keep_params={}):
14         if apiconfig is None:
15             apiconfig = config.settings()
16         self.apiconfig = copy.copy(apiconfig)
17         self.local = threading.local()
18         self.keep = keep.KeepClient(api_client=self, **keep_params)
19
20     def localapi(self):
21         if 'api' not in self.local.__dict__:
22             self.local.api = api.api('v1', False, apiconfig=self.apiconfig)
23         return self.local.api
24
25     def __getattr__(self, name):
26         # Proxy nonexistent attributes to the thread-local API client.
27         if name == "api_token":
28             return self.apiconfig['ARVADOS_API_TOKEN']
29         try:
30             return getattr(self.localapi(), name)
31         except AttributeError:
32             return super(SafeApi, self).__getattr__(name)