-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexo2_api_request.py
106 lines (85 loc) · 2.95 KB
/
exo2_api_request.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import functools
from logging import (
getLogger,
INFO,
StreamHandler,
)
import json
import os
logger = getLogger()
logger.setLevel(INFO)
ch = StreamHandler()
logger.addHandler(ch)
AUTHORIZATION_CODE = 911
def all_method(method, auth, data, name, url):
"""emulate a rest or rpc request on url"""
if auth == AUTHORIZATION_CODE:
return f"authorized {method} request of {data} on {name} {url}"
else:
return f"!! UNAUTHORIZED !!, auth = {auth} on {name} {url}"
def rest_wrapper(method):
def wrapped(auth, data, name, url):
return all_method(method, auth, data, name, url)
return wrapped
class RestRequest():
"""
this is our mock of python requests library
use:
RestRequest.<method>(auth, data, name, url)
<method> in ('get', 'post', 'put', 'delete')
RestRequest work with class methods only
"""
def __new__(cls, *methods):
for method in methods:
setattr(
cls,
method,
staticmethod(rest_wrapper(method))
)
return cls
r = RestRequest('get', 'post', 'put', 'delete')
class RestClient():
def __init__(self, client_name, url, auth=None):
self.client_name = client_name
self.url = url
self.auth = auth
def _do_operation # TODO complete args in signature?
data = json.dumps(kwargs.get("data", {}))
endpoint = os.path.join(self.url, api_path.format(**kwargs))
# TODO write call to RestRequest
logger.info(
f"===============================\n"
f'RestClient._do_operation\n'
f'on method: {method_name}\n'
f'on path: {api_path}\n'
f"with result: {response}\n"
f"===============================\n"
)
return response
def api_request(method_name, api_path):
def outer_wrapper(func):
@functools.wraps(func)
def method_wrapper # TODO write signature args
# + amc authent: not implemented here for simplicity)
logger.info(
f"api_request decorator on:\n"
f"************** {func.__name__} **************\n"
f"with with keyword arguments: {kwargs}\n"
)
return self._do_operation # TODO write args to call?
return method_wrapper
return outer_wrapper
class Contentd(RestClient):
def __init__(self, client_name, url, auth):
super().__init__(client_name, url, auth)
@api_request('get', 'contentd/cdn_prefix/{cdn_prefix_id}')
def get_cdn_prefix(self, cdn_prefix_id):
""""""
@api_request('put', 'contentd/cdn_prefix/{cdn_prefix_id}')
def update_cdn_prefix(self, cdn_prefix_id, data):
""""""
if __name__ == '__main__':
c = Contentd('contentd', 'url', 911)
c.get_cdn_prefix(cdn_prefix_id=5)
c = Contentd('contentd', 'url', 911)
c.update_cdn_prefix(cdn_prefix_id=5, data={'prefix':'my prefix'})