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