apppublic/appPublic/oauth_client.py
2024-04-06 13:43:28 +08:00

84 lines
2.4 KiB
Python

import json
from appPublic.httpclient import HttpClient, RESPONSE_TEXT, RESPONSE_JSON, RESPONSE_BIN,RESPONSE_FILE, RESPONSE_STREAM
from appPublic.argsConvert import ArgsConvert
class OAuthClient:
def __init__(self, desc, chunk_handle=None):
assert desc.get('data')
assert desc.get('mapis')
self.desc = desc
self.data = desc.get('data')
self.mapis = desc.get('mapis')
self.mkeys = self.mapis.keys()
self._chunk_handle = chunk_handle
self.ac = ArgsConvert('${', '}')
def stream_handle(self, chunk):
if self._chunk_handle:
self._chunk_handle(chunk)
else:
self.chunk_data = self.chunk_data + chunk
async def __call__(self, mapi, params):
self.chunk_data = ''
if mapi not in self.mkeys:
raise Exception(f'{mapi} not defined')
d = self.mapis[mapi]
assert d.get('url')
method = d.get('method', 'GET')
headers = {}
for h in d.get('headers',{}):
headers[h.get('name')] = h.get('value')
mydata = {}
for p in d.get('data', {}):
mydata[p.get('name')] = p.get('value')
myparams = {}
for p in d.get('params', {}):
myparams[p.get('name')] = p.get('value')
url = d.get('url')
_params = self.datalize(myparams, params)
_headers = self.datalize(headers, params)
_data = self.datalize(mydata, params)
response_type = RESPONSE_STREAM
hc = HttpClient()
print(f'{url=}, {method=}, {_params=}, {_data=}, {_headers=}')
resp_data = await hc.request(url, method, response_type=response_type,
params=_params,
data=None if _data == {} else json.dumps(_data),
stream_func=self.stream_handle,
headers=_headers)
if not self._chunk_handle:
resp_data = self.chunk_data
if resp_data is None:
raise Exception(f'request error:{url=}\n{method=}\n{response_type=}\n{_params=}\n{_headers=}')
errfield = d.get('error_field')
err = resp_data.get(errfield)
if err:
msg = resp_data.get(d.get('error_msg_field'))
raise Exception(f'Error:{url}\n{msg}')
respdesc= d.get('resp_set_data', [])
for r in respdesc:
v = resp_data[r['field']]
k = r['name']
self.data[k] = v
return resp_data
def datalize(self, dic, data={}):
mydata = self.data.copy()
mydata.update(data)
s1 = self.ac.convert(dic, mydata)
return s1
def is_error(self, resp_data, error_field):
if resp_data.get(error_feield):
return True
def set_data(self, resp_data, data_desc):
for dd in data_desc:
f = dd['field']
n = dd['name']
if resp_data.get(f):
self.data[n] = resp_data[f]