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