factory/apps/third/king/k.py

80 lines
3.0 KiB
Python

import logging
import traceback
import uuid
import requests
from requests.exceptions import RequestException
from django.conf import settings
from rest_framework.exceptions import APIException, ParseError
from apps.third.errors import KING_REQUEST_ERROR
from apps.utils.tools import print_roundtrip
from django.utils.timezone import now
from apps.third.king import king_api
from apps.utils.tools import singleton
from django.core.cache import cache
from apps.third.mixins import HandleLogMixin
requests.packages.urllib3.disable_warnings()
myLogger = logging.getLogger('log')
@singleton
class KingClient(HandleLogMixin):
"""
亚控数采
"""
def __init__(self) -> None:
self.king_enabled = getattr(settings, 'KING_ENABLED', False)
if self.king_enabled:
self.headers = {}
self.log = {}
# self._get_token()
def _get_token(self):
king_token = cache.get('king_token', None)
if king_token:
is_ok, _ = self.request(
**king_api['heartbeat'], headers={'Authorization': king_token}, raise_exception=False, timeout=10)
if is_ok == 'success':
return
json = {
'username': settings.KING_USERNAME,
'password': settings.KING_PASSWORD
}
_, res = self.request(
**king_api['login'], json=json, timeout=10)
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):
if not self.king_enabled:
raise ParseError('亚控对接未启用')
self.headers['Authorization'] = cache.get('king_token', '')
self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
"params": params, "body": json, "target": "king", "result": 10, "headers": self.headers}
try:
r = getattr(requests, method)('{}{}'.format(settings.KING_BASE_URL, url),
headers=self.headers, params=params, json=json, timeout=timeout, verify=False)
# if settings.DEBUG:
# print_roundtrip(r)
ret = r.text
if 300 > r.status_code >= 200:
ret = r.json()
if ret['code'] != 0:
err_detail = dict(detail='亚控错误:' + '|'.join(ret['message']),
code='king_' + str(ret['code']))
self.handle_log(result='fail', response=ret)
if raise_exception:
raise ParseError(**err_detail)
return 'fail', err_detail
return 'success', ret['data']
else:
self.handle_log(result='error', response=ret)
except RequestException:
self.handle_log(result='error', errors=traceback.format_exc())
if raise_exception:
raise APIException(**KING_REQUEST_ERROR)
return 'error', KING_REQUEST_ERROR
kingClient = KingClient()