-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
executable file
·153 lines (100 loc) · 4.59 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3
"""Python requests for ALPFS testing
To run:
./client.py
"""
import argparse
import logging
import requests
class APIClient(object):
def __init__(self, a_host, a_port=80, a_schema='http', an_api_version='api/v0', use_verify=True):
"""Construct a ALPFS API client
Args:
a_host (str): FQDN or IP address of director
a_port (int): ssh port
a_schema (str): http or https
use_verify (bool): use certificate verification (usually False)
"""
self.host = a_host
self.port = a_port
self.schema = a_schema
self.api_version = an_api_version
self.verify = use_verify
self.headers = dict()
self.headers['content-type'] = 'application/json'
self.headers['cache-control'] = 'no-cache'
return
def compose_api_url(self, a_url):
"""Build API URL from parts"""
return '{}://{}:{}/{}/{}'.format(self.schema, self.host, self.port, self.api_version, a_url)
def get(self, a_url, params=None, headers=None):
"""GET action
Args:
a_url (str): url
params (dict): GET parameters
headers(dict): request headers
Returns: request.get()
"""
an_endpoint = self.compose_api_url(a_url)
logging.debug('GET %s headers: %s, params: %s', an_endpoint, headers, params)
return requests.get(an_endpoint, params=params, headers=headers, verify=self.verify)
def post(self, a_url, headers=None, json=None, files=None):
"""POST action
TODO data arg vs. json?
Args:
a_url (str): url
json (json): json data to post
files (dict): files = {'file': open('somefile.csv', 'rb')}
headers(dict): request headers
Returns: request.post()
"""
an_endpoint = self.compose_api_url(a_url)
logging.debug('POST %s headers: %s, JSON:%s, files:%s', an_endpoint, headers, json, files)
return requests.post(an_endpoint, headers=headers, json=json, files=files, verify=self.verify)
# ================
# ===== main =====
# ================
if __name__ == '__main__':
loglevels = {'debug': logging.DEBUG,
'info': logging.INFO,
'warn': logging.WARN,
'error': logging.ERROR}
defaults = {'host':'localhost',
'loglevel': 'warn',
'schema': 'http',
'port': 80,
'use_verify': False}
parser = argparse.ArgumentParser(description='alpine linux python flask server')
parser.add_argument('--host', type=str, dest='host', default=defaults['host'],
metavar='host',
help='FQDN or IP of host (default: %(default)s)')
parser.add_argument('-l', '--loglevel', choices=list(loglevels.keys()),
dest='loglevel', default=defaults['loglevel'],
metavar='LEVEL',
help='logging level choice: %(keys)s (default: %(default)s)' % {
'keys':', '.join(list(loglevels.keys())), 'default':'%(default)s'})
parser.add_argument('-p', '--port', type=int, dest='port', default=defaults['port'],
help='port (default: %(default)s)')
parser.add_argument('--schema', type=str, dest='schema', default=defaults['schema'],
metavar='schema',
help='schema (default: %(default)s)')
parser.add_argument('--use_verify', action='store_true',
dest='use_verify', default=defaults['use_verify'],
help='use_verify (default: %(default)s)')
args = parser.parse_args()
# ----- set up default logging -----
log_handler = logging.StreamHandler()
log_handler.setFormatter(
logging.Formatter(
'[%(asctime)s %(levelname)s %(filename)s %(lineno)s] %(message)s'))
logging.getLogger().addHandler(log_handler)
logging.getLogger().setLevel(loglevels[args.loglevel])
# -------------------
# ----- run app -----
# -------------------
# TODO /api/v0 added by this client won't work for http get foo = a_client.get('', an_api_version='')
a_client = APIClient(args.host, args.port, a_schema=args.schema, use_verify=args.use_verify)
a_response = a_client.get('whoami', params={'name':'alpfs', 'e':2.7182})
print('GET /api/v0/whoami', a_response.json())
a_response = a_client.post('whoareyou', json={'name':'lrmcfarland', 'uri':'starbug.com'})
print('POST /api/v0/whoareyou', a_response.json())