用redis保存第三方token

This commit is contained in:
曹前明 2022-10-04 20:33:29 +08:00
parent 38b5512001
commit 9c4388da78
4 changed files with 14 additions and 12 deletions

View File

@ -16,6 +16,7 @@ from apps.utils.tools import convert_to_base64, print_roundtrip
from django.utils.timezone import now from django.utils.timezone import now
from apps.third.tapis import dhapis from apps.third.tapis import dhapis
from apps.utils.tools import singleton from apps.utils.tools import singleton
from django.core.cache import cache
requests.packages.urllib3.disable_warnings() requests.packages.urllib3.disable_warnings()
myLogger = logging.getLogger('log') myLogger = logging.getLogger('log')
@ -34,7 +35,6 @@ class DhClient:
self.client_secret = client_secret self.client_secret = client_secret
self.headers = {"Connection": "close"} self.headers = {"Connection": "close"}
self.isGetingToken = False self.isGetingToken = False
self.token = None
self.log = {} self.log = {}
self._get_token() self._get_token()
@ -47,15 +47,15 @@ class DhClient:
} }
is_ok, res = self.request(**dhapis['token_login'], params=params, raise_exception=False) is_ok, res = self.request(**dhapis['token_login'], params=params, raise_exception=False)
if is_ok == 'success': if is_ok == 'success':
self.token = res['access_token'] cache.set('dh_token', res['access_token'])
self.headers['Authorization'] = 'bearer ' + res['access_token']
self.headers['User-Id'] = '1'
self.isGetingToken = False self.isGetingToken = False
def request(self, url: str, method: str, params=dict(), json=dict(), timeout=120, def request(self, url: str, method: str, params=dict(), json=dict(), timeout=120,
file_path_rela=None, raise_exception=True): file_path_rela=None, raise_exception=True):
if not settings.DAHUA_ENABLED: if not settings.DAHUA_ENABLED:
raise ParseError('大华对接未启用') raise ParseError('大华对接未启用')
self.headers['Authorization'] = 'bearer ' + cache.get('dh_token', '')
self.headers['User-Id'] = '1'
self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method, self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
"params": params, "body": json, "target": "dahua", "result": 10, "headers": self.headers} "params": params, "body": json, "target": "dahua", "result": 10, "headers": self.headers}
files = None files = None
@ -111,7 +111,7 @@ class DhClient:
def get_full_pic(self, path: str): def get_full_pic(self, path: str):
"""返回完整访问地址 """返回完整访问地址
""" """
return '{}/evo-apigw/evo-oss/{}?token={}'.format(settings.DAHUA_BASE_URL, path, self.token) return '{}/evo-apigw/evo-oss/{}?token={}'.format(settings.DAHUA_BASE_URL, path, cache.get('dh_token', ''))
def snap(self, code: str): def snap(self, code: str):
"""摄像头实时截图 """摄像头实时截图

View File

@ -14,7 +14,7 @@ from apps.utils.tools import print_roundtrip, ranstr
from apps.third.tapis import spapis from apps.third.tapis import spapis
from django.utils.timezone import now from django.utils.timezone import now
from apps.utils.tools import singleton from apps.utils.tools import singleton
from django.core.cache import cache
requests.packages.urllib3.disable_warnings() requests.packages.urllib3.disable_warnings()
myLogger = logging.getLogger('log') myLogger = logging.getLogger('log')
@ -46,13 +46,14 @@ class SpClient:
} }
is_ok, res = self.request(**spapis['user_login'], json=json_data, raise_exception=False) is_ok, res = self.request(**spapis['user_login'], json=json_data, raise_exception=False)
if is_ok == 'success': if is_ok == 'success':
self.headers['Authorization'] = 'Bearer ' + res['user']['token'] cache.set('sp_token', res['user']['token'])
self.isGetingToken = False self.isGetingToken = False
def request(self, url: str, method: str, params=dict(), json=dict(), timeout=120, def request(self, url: str, method: str, params=dict(), json=dict(), timeout=120,
file_path_rela=None, raise_exception=True): file_path_rela=None, raise_exception=True):
if not settings.SP_ENABLED: if not settings.SP_ENABLED:
raise ParseError('音响对接未启用') raise ParseError('音响对接未启用')
self.headers['Authorization'] = 'Bearer ' + cache.get('sp_token', '')
self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method, self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
"params": params, "body": json, "target": "speaker", "result": 10, "headers": self.headers} "params": params, "body": json, "target": "speaker", "result": 10, "headers": self.headers}
files = None files = None

View File

@ -21,6 +21,7 @@ from rest_framework import serializers
from django.conf import settings from django.conf import settings
import stomp import stomp
from django.conf import settings from django.conf import settings
from django.core.cache import cache
myLogger = logging.getLogger('log') myLogger = logging.getLogger('log')
# Create your views here. # Create your views here.
@ -160,7 +161,7 @@ class XxCommonViewSet(CreateModelMixin, CustomGenericViewSet):
获取token 获取token
""" """
return Response({'token': xxClient.token}) return Response({'token': cache.get('xx_token', '')})
@action(methods=['post'], detail=False, @action(methods=['post'], detail=False,
permission_classes=[IsAdminUser], permission_classes=[IsAdminUser],
@ -266,7 +267,7 @@ class DhCommonViewSet(CreateModelMixin, CustomGenericViewSet):
获取token 获取token
""" """
return Response({'token': dhClient.token, 'header': dhClient.headers}) return Response({'token': cache.get('dh_token', '')})
@action(methods=['post'], detail=False, @action(methods=['post'], detail=False,
permission_classes=[IsAuthenticated], permission_classes=[IsAuthenticated],

View File

@ -13,6 +13,7 @@ from apps.utils.tools import print_roundtrip
from django.utils.timezone import now from django.utils.timezone import now
from apps.third.tapis import xxapis from apps.third.tapis import xxapis
from apps.utils.tools import singleton from apps.utils.tools import singleton
from django.core.cache import cache
requests.packages.urllib3.disable_warnings() requests.packages.urllib3.disable_warnings()
myLogger = logging.getLogger('log') myLogger = logging.getLogger('log')
@ -29,7 +30,6 @@ class XxClient:
self.username = username self.username = username
self.isGetingToken = False self.isGetingToken = False
self.headers = {"Connection": "close"} self.headers = {"Connection": "close"}
self.token = ''
self.log = {} self.log = {}
self._get_token() self._get_token()
@ -40,13 +40,13 @@ class XxClient:
} }
is_ok, res = self.request(**xxapis['token_login'], json=json, raise_exception=False) is_ok, res = self.request(**xxapis['token_login'], json=json, raise_exception=False)
if is_ok == 'success': if is_ok == 'success':
self.token = res['token'] cache.set('xx_token', res['token'])
self.isGetingToken = False self.isGetingToken = False
def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True): def request(self, url: str, method: str = 'post', params=dict(), json=dict(), timeout=20, raise_exception=True):
if not settings.XX_ENABLED: if not settings.XX_ENABLED:
raise ParseError('寻息对接未启用') raise ParseError('寻息对接未启用')
params['accessToken'] = self.token params['accessToken'] = cache.get('xx_token', '')
json['username'] = self.username json['username'] = self.username
json['buildId'] = settings.XX_BUILDID json['buildId'] = settings.XX_BUILDID
json['licence'] = settings.XX_LICENCE json['licence'] = settings.XX_LICENCE