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