fix: king request 6

This commit is contained in:
caoqianming 2024-04-25 21:37:58 +08:00
parent dd61b1ba01
commit 932ef2d2c8
1 changed files with 11 additions and 7 deletions

View File

@ -35,16 +35,20 @@ class KingClient(HandleLogMixin):
# is_ok, _ = self.request(**kapis['heartbeat'], raise_exception=False, timeout=10) # is_ok, _ = self.request(**kapis['heartbeat'], raise_exception=False, timeout=10)
# if is_ok == 'success': # if is_ok == 'success':
# return # return
if cache.get('king_token') != 'requesting': current_val = cache.get('king_token')
if current_val != 'requesting':
json = { json = {
'username': settings.KING_USERNAME, 'username': settings.KING_USERNAME,
'password': settings.KING_PASSWORD 'password': settings.KING_PASSWORD
} }
try:
cache.set('king_token', 'requesting', timeout=None) cache.set('king_token', 'requesting', timeout=None)
_, res = self.request( _, res = self.request(
**kapis['login'], json=json, timeout=10, need_auth=False) **kapis['login'], json=json, timeout=10, need_auth=False)
cache.set('king_token', res['Authorization'], timeout=None) cache.set('king_token', res['Authorization'], timeout=None)
except Exception:
cache.set('king_token', current_val, timeout=None)
cache.set('king_token', res['Authorization'], timeout=None)
def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True, need_auth=True): def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True, need_auth=True):
if not self.king_enabled: if not self.king_enabled:
@ -55,6 +59,7 @@ class KingClient(HandleLogMixin):
token = cache.get('king_token') token = cache.get('king_token')
if token != 'requesting': if token != 'requesting':
self.headers['Authorization'] = token self.headers['Authorization'] = token
break
time.sleep(0.5) time.sleep(0.5)
count = count -1 count = count -1
@ -68,12 +73,11 @@ class KingClient(HandleLogMixin):
ret = r.text ret = r.text
if 300 > r.status_code >= 200: if 300 > r.status_code >= 200:
ret = r.json() ret = r.json()
myLogger.info(url, ret)
if 'code' in ret: if 'code' in ret:
if ret['code'] != 0: if ret['code'] != 0:
if need_auth and ret['code'] in [-1, -2]: # 认证失败 if need_auth and ret['code'] in [-1, -2]: # 认证失败
self._get_token() self._get_token()
self.request(url, method, params, json, timeout, raise_exception, check_auth=False) self.request(url, method, params, json, timeout, raise_exception, need_auth=False)
return return
err_detail = dict(detail=f"亚控错误: {ret['message']}", err_detail = dict(detail=f"亚控错误: {ret['message']}",
code='king_' + str(ret['code'])) code='king_' + str(ret['code']))