This repository has been archived by the owner on Jul 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.py
62 lines (50 loc) · 2.04 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import requests
class ButlerClient(object):
"""ButlerClient is function factory for a Butler server.
for each function in the Butler server, there is equvivalent function in the client
with the same parameters, and can send the request to the Butler instance
"""
def __init__(self, butler, url):
"""Init properties.
:param server: Butler instance
"""
self.url = url.rstrip('/')
self.butler = butler
self.functions = {}
self.session = requests.Session()
self.response = None
def _get_function(self, function_name):
"""get ButlerFunction instance by it's name."""
for func in self.butler.functions:
if func.function_name == function_name:
return func
def __getattr__(self, name):
"""Override the original __getattr__ to have auto-generated function.
:param name: name of required function
"""
# use cache functions
if name in self.functions:
return self.functions[name]
# validae function in Butler Server
func = self._get_function(name)
if not func:
raise AttributeError
# create new function from ButlerFunction object
def client_func(*args, **kwargs):
params = []
args = list(args) # args is tuple, which is immutable
for arg in func.args:
if arg in kwargs or not args:
try:
params.append(kwargs.pop(arg))
except KeyError:
params.append(func.get_default(arg)) # adding default to avoid missing parameter
else:
params.append(args.pop(0))
url = self.url + func.get_url(params)
self.response = self.session.request(func.method, url, *args, **kwargs)
return self.response
client_func.__name__ = name
client_func.__doc__ = func.obj.__doc__
self.functions[name] = client_func
return client_func