feat: kingclient优化
This commit is contained in:
parent
9600e95272
commit
7d8585856d
|
@ -13,6 +13,7 @@ from apps.third.king.king_api import kapis
|
|||
from apps.utils.tools import singleton
|
||||
from django.core.cache import cache
|
||||
from apps.third.mixins import HandleLogMixin
|
||||
import time
|
||||
requests.packages.urllib3.disable_warnings()
|
||||
myLogger = logging.getLogger('log')
|
||||
|
||||
|
@ -38,20 +39,21 @@ class KingClient(HandleLogMixin):
|
|||
'username': settings.KING_USERNAME,
|
||||
'password': settings.KING_PASSWORD
|
||||
}
|
||||
cache.set('king_token_request', 'requesting')
|
||||
_, res = self.request(
|
||||
**kapis['login'], json=json, timeout=10)
|
||||
old_token = cache.get('king_token', '')
|
||||
cache.set('king_token', res['Authorization'], timeout=None)
|
||||
if old_token:
|
||||
self.request(**kapis['logout'], authorization=old_token, raise_exception=False)
|
||||
cache.set('king_token_request', 'done')
|
||||
|
||||
def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True, authorization=''):
|
||||
def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True):
|
||||
if not self.king_enabled:
|
||||
raise ParseError('亚控对接未启用')
|
||||
if authorization:
|
||||
self.headers['Authorization'] = authorization
|
||||
else:
|
||||
self.headers['Authorization'] = cache.get('king_token', '')
|
||||
count = 6
|
||||
while cache.get('king_token_request', None) == 'requesting':
|
||||
time.sleep(0.5)
|
||||
count = count - 1
|
||||
if count < 0:
|
||||
break
|
||||
self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
|
||||
"params": params, "body": json, "target": "king", "result": 10, "headers": self.headers}
|
||||
try:
|
||||
|
@ -64,6 +66,10 @@ class KingClient(HandleLogMixin):
|
|||
ret = r.json()
|
||||
if 'code' in ret:
|
||||
if ret['code'] != 0:
|
||||
if ret['code'] in [-1, -2]: # 认证失败
|
||||
self._get_token()
|
||||
self.request(url, method, params, json, timeout, raise_exception)
|
||||
return
|
||||
err_detail = dict(detail=f"亚控错误: {ret['message']}",
|
||||
code='king_' + str(ret['code']))
|
||||
self.handle_log(result='fail', response=ret)
|
||||
|
|
Loading…
Reference in New Issue