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