apppublic/appPublic/oauth_client.py
2024-03-20 18:15:10 +08:00

74 lines
2.1 KiB
Python

import json
from appPublic.httpclient import HttpClient, RESPONSE_TEXT, RESPONSE_JSON, RESPONSE_BIN,RESPONSE_FILE
from appPublic.argsConvert import ArgsConvert
class OAuthClient:
def __init__(self, desc):
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.ac = ArgsConvert('${', '}')
async def __call__(self, mapi, params):
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 = d.get('response_type', RESPONSE_JSON)
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),
headers=_headers)
print(f'{resp_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]