-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.py
executable file
·241 lines (205 loc) · 9.31 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
############################################################
#
# Autogenerated by the KBase type compiler -
# any changes made here will be overwritten
#
############################################################
try:
import json as _json
except ImportError:
import sys
sys.path.append('simplejson-2.3.3')
import simplejson as _json
import requests as _requests
import urlparse as _urlparse
import random as _random
import base64 as _base64
from ConfigParser import ConfigParser as _ConfigParser
import os as _os
_CT = 'content-type'
_AJ = 'application/json'
_URL_SCHEME = frozenset(['http', 'https'])
def _get_token(user_id, password,
auth_svc='https://nexus.api.globusonline.org/goauth/token?' +
'grant_type=client_credentials'):
# This is bandaid helper function until we get a full
# KBase python auth client released
auth = _base64.encodestring(user_id + ':' + password)
headers = {'Authorization': 'Basic ' + auth}
ret = _requests.get(auth_svc, headers=headers, allow_redirects=True)
status = ret.status_code
if status >= 200 and status <= 299:
tok = _json.loads(ret.text)
elif status == 403:
raise Exception('Authentication failed: Bad user_id/password ' +
'combination for user %s' % (user_id))
else:
raise Exception(ret.text)
return tok['access_token']
def _read_rcfile(file=_os.environ['HOME'] + '/.authrc'): # @ReservedAssignment
# Another bandaid to read in the ~/.authrc file if one is present
authdata = None
if _os.path.exists(file):
try:
with open(file) as authrc:
rawdata = _json.load(authrc)
# strip down whatever we read to only what is legit
authdata = {x: rawdata.get(x) for x in (
'user_id', 'token', 'client_secret', 'keyfile',
'keyfile_passphrase', 'password')}
except Exception as e:
print("Error while reading authrc file %s: %s" % (file, e))
return authdata
def _read_inifile(file=_os.environ.get( # @ReservedAssignment
'KB_DEPLOYMENT_CONFIG', _os.environ['HOME'] +
'/.kbase_config')):
# Another bandaid to read in the ~/.kbase_config file if one is present
authdata = None
if _os.path.exists(file):
try:
config = _ConfigParser()
config.read(file)
# strip down whatever we read to only what is legit
authdata = {x: config.get('authentication', x)
if config.has_option('authentication', x)
else None for x in ('user_id', 'token',
'client_secret', 'keyfile',
'keyfile_passphrase', 'password')}
except Exception as e:
print("Error while reading INI file %s: %s" % (file, e))
return authdata
class ServerError(Exception):
def __init__(self, name, code, message, data=None, error=None):
self.name = name
self.code = code
self.message = '' if message is None else message
self.data = data or error or ''
# data = JSON RPC 2.0, error = 1.1
def __str__(self):
return self.name + ': ' + str(self.code) + '. ' + self.message + \
'\n' + self.data
class _JSONObjectEncoder(_json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, frozenset):
return list(obj)
return _json.JSONEncoder.default(self, obj)
class mineDatabaseServices(object):
def __init__(self, url=None, timeout=30 * 60, user_id=None,
password=None, token=None, ignore_authrc=False,
trust_all_ssl_certificates=False):
if url is None:
raise ValueError('A url is required')
scheme, _, _, _, _, _ = _urlparse.urlparse(url)
if scheme not in _URL_SCHEME:
raise ValueError(url + " isn't a valid http url")
self.url = url
self.timeout = int(timeout)
self._headers = dict()
self.trust_all_ssl_certificates = trust_all_ssl_certificates
# token overrides user_id and password
if token is not None:
self._headers['AUTHORIZATION'] = token
elif user_id is not None and password is not None:
self._headers['AUTHORIZATION'] = _get_token(user_id, password)
elif 'KB_AUTH_TOKEN' in _os.environ:
self._headers['AUTHORIZATION'] = _os.environ.get('KB_AUTH_TOKEN')
elif not ignore_authrc:
authdata = _read_inifile()
if authdata is None:
authdata = _read_rcfile()
if authdata is not None:
if authdata.get('token') is not None:
self._headers['AUTHORIZATION'] = authdata['token']
elif(authdata.get('user_id') is not None
and authdata.get('password') is not None):
self._headers['AUTHORIZATION'] = _get_token(
authdata['user_id'], authdata['password'])
if self.timeout < 1:
raise ValueError('Timeout value must be at least 1 second')
def _call(self, method, params):
arg_hash = {'method': method,
'params': params,
'version': '1.1',
'id': str(_random.random())[2:]
}
body = _json.dumps(arg_hash, cls=_JSONObjectEncoder)
ret = _requests.post(self.url, data=body, headers=self._headers,
timeout=self.timeout,
verify=not self.trust_all_ssl_certificates)
if ret.status_code == _requests.codes.server_error:
if _CT in ret.headers and ret.headers[_CT] == _AJ:
err = _json.loads(ret.text)
if 'error' in err:
raise ServerError(**err['error'])
else:
raise ServerError('Unknown', 0, ret.text)
else:
raise ServerError('Unknown', 0, ret.text)
if ret.status_code != _requests.codes.OK:
ret.raise_for_status()
resp = _json.loads(ret.text)
if 'result' not in resp:
raise ServerError('Unknown', 0, 'An unknown server error occurred')
return resp['result']
def model_search(self, query):
resp = self._call('mineDatabaseServices.model_search',
[query])
return resp[0]
def quick_search(self, db, query):
resp = self._call('mineDatabaseServices.quick_search',
[db, query])
return resp[0]
def similarity_search(self, db, comp_structure, min_tc, fp_type, limit, parent_filter, reaction_filter):
resp = self._call('mineDatabaseServices.similarity_search',
[db, comp_structure, min_tc, fp_type, limit, parent_filter, reaction_filter])
return resp[0]
def structure_search(self, db, input_format, comp_structure, parent_filter, reaction_filter):
resp = self._call('mineDatabaseServices.structure_search',
[db, input_format, comp_structure, parent_filter, reaction_filter])
return resp[0]
def substructure_search(self, db, substructure, limit, parent_filter, reaction_filter):
resp = self._call('mineDatabaseServices.substructure_search',
[db, substructure, limit, parent_filter, reaction_filter])
return resp[0]
def database_query(self, db, mongo_query, parent_filter, reaction_filter):
resp = self._call('mineDatabaseServices.database_query',
[db, mongo_query, parent_filter, reaction_filter])
return resp[0]
def get_ids(self, db, collection, query):
resp = self._call('mineDatabaseServices.get_ids',
[db, collection, query])
return resp[0]
def get_comps(self, db, ids):
resp = self._call('mineDatabaseServices.get_comps',
[db, ids])
return resp[0]
def get_rxns(self, db, ids):
resp = self._call('mineDatabaseServices.get_rxns',
[db, ids])
return resp[0]
def get_ops(self, db, operator_names):
resp = self._call('mineDatabaseServices.get_ops',
[db, operator_names])
return resp[0]
def get_operator(self, db, operator_name):
resp = self._call('mineDatabaseServices.get_operator',
[db, operator_name])
return resp[0]
def get_adducts(self):
resp = self._call('mineDatabaseServices.get_adducts',
[])
return resp[0]
def ms_adduct_search(self, text, text_type, ms_params):
resp = self._call('mineDatabaseServices.ms_adduct_search',
[text, text_type, ms_params])
return resp[0]
def ms2_search(self, text, text_type, ms_params):
resp = self._call('mineDatabaseServices.ms2_search',
[text, text_type, ms_params])
return resp[0]
def pathway_search(self, db, start_comp, end_comp, len_limit, all_paths):
resp = self._call('mineDatabaseServices.pathway_search',
[db, start_comp, end_comp, len_limit, all_paths])
return resp[0]