import time from threading import Thread import requests from django.conf import settings from rest_framework.exceptions import APIException, ParseError from apps.utils.errors import DH_REQUEST_ERROR from apps.utils.tools import print_roundtrip requests.packages.urllib3.disable_warnings() class DhClient: """ 大华 """ def __init__(self, client_id=settings.DAHUA_CLIENTID, client_secret=settings.DAHUA_SECRET) -> None: if settings.DAHUA_ENABLED: self.client_id = client_id self.client_secret = client_secret self.headers = {} self.isGetingToken = False self.isRuning = True self.token = None self.t = None # 线程 self.setup() def _get_token_loop(self): while self.isRuning: params = { 'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret } r = requests.post(params=params, url=settings.DAHUA_BASE_URL + '/evo-apigw/evo-oauth/oauth/token', verify=False) ret = r.json() if ret['success']: self.token = ret['data']['access_token'] self.headers['Authorization'] = 'bearer ' + ret['data']['access_token'] self.headers['User-Id'] = '1' time.sleep(3600) def setup(self): t = Thread(target=self._get_token_loop, args=(), daemon=True) t.start() def __del__(self): """ 自定义销毁 """ self.isRuning = False # self.t.join() def request(self, url: str, method: str, params=dict(), json=dict(), timeout=10, file_path_rela=None, raise_exception=True): if not settings.DAHUA_ENABLED: raise ParseError('大华对接未启用') files = None if file_path_rela: # 相对路径 files = {'file': open(settings.BASE_DIR + file_path_rela, 'rb')} try: if params: url = url.format(**params) r = getattr(requests, method)('{}{}'.format(settings.DAHUA_BASE_URL, url), headers=self.headers, params=params, json=json, timeout=timeout, files=files, verify=False) except Exception: if raise_exception: raise APIException(**DH_REQUEST_ERROR) return 'error', DH_REQUEST_ERROR # if settings.DEBUG: # print_roundtrip(r) if r.status_code == 200: ret = r.json() if ret.get('code') == '27001007': self.get_token() # 重新获取token self.request(url, method, params, json, timeout, file_path_rela, raise_exception) else: if ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]: detail = '大华错误:' + \ '{}|{}{}{}'.format(str(ret['code']), ret.get('errMsg', ''), ret.get('desc', ''), str(ret.get('data', ''))) err_detail = dict(detail=detail, code='dh_'+str(ret['code'])) if raise_exception: raise ParseError(**err_detail) return 'fail', dict(detail=detail, code='dh_'+str(ret['code'])) return 'success', ret['data'] if 'data' in ret else None if raise_exception: raise APIException(**DH_REQUEST_ERROR) return 'error', DH_REQUEST_ERROR