三方接口调用日志
This commit is contained in:
parent
71da2960a2
commit
16c46902c1
|
|
@ -1,6 +1,6 @@
|
||||||
from apps.utils.xunxi import XxClient
|
from apps.third.xunxi import XxClient
|
||||||
from apps.utils.dahua import DhClient
|
from apps.third.dahua import DhClient
|
||||||
from apps.utils.speaker import SpClient
|
from apps.third.speaker import SpClient
|
||||||
dhClient = DhClient()
|
dhClient = DhClient()
|
||||||
xxClient = XxClient()
|
xxClient = XxClient()
|
||||||
spClient = SpClient()
|
spClient = SpClient()
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,15 @@
|
||||||
import time
|
import time
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
import uuid
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from rest_framework.exceptions import APIException, ParseError
|
from rest_framework.exceptions import APIException, ParseError
|
||||||
|
|
||||||
from apps.utils.errors import DH_REQUEST_ERROR
|
from apps.third.errors import DH_REQUEST_ERROR
|
||||||
|
from apps.third.models import Tlog
|
||||||
from apps.utils.tools import print_roundtrip
|
from apps.utils.tools import print_roundtrip
|
||||||
|
from django.utils.timezone import now
|
||||||
|
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
|
|
||||||
|
|
@ -26,6 +29,7 @@ class DhClient:
|
||||||
self.isRuning = True
|
self.isRuning = True
|
||||||
self.token = None
|
self.token = None
|
||||||
self.t = None # 线程
|
self.t = None # 线程
|
||||||
|
self.log = {}
|
||||||
self.setup()
|
self.setup()
|
||||||
|
|
||||||
def _get_token_loop(self):
|
def _get_token_loop(self):
|
||||||
|
|
@ -59,16 +63,20 @@ class DhClient:
|
||||||
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.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
|
||||||
|
"params": params, "body": json, "target": "dahua", "result": 10}
|
||||||
files = None
|
files = None
|
||||||
if file_path_rela: # 相对路径
|
if file_path_rela: # 相对路径
|
||||||
files = {'file': open(settings.BASE_DIR + file_path_rela, 'rb')}
|
files = {'file': open(settings.BASE_DIR + file_path_rela, 'rb')}
|
||||||
try:
|
try:
|
||||||
if params:
|
if params:
|
||||||
url = url.format(**params)
|
url = url.format(**params)
|
||||||
|
self.log.update({"path": url})
|
||||||
r = getattr(requests, method)('{}{}'.format(settings.DAHUA_BASE_URL, url),
|
r = getattr(requests, method)('{}{}'.format(settings.DAHUA_BASE_URL, url),
|
||||||
headers=self.headers, params=params, json=json,
|
headers=self.headers, params=params, json=json,
|
||||||
timeout=timeout, files=files, verify=False)
|
timeout=timeout, files=files, verify=False)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
self.handle_log(result='error')
|
||||||
if raise_exception:
|
if raise_exception:
|
||||||
raise APIException(**DH_REQUEST_ERROR)
|
raise APIException(**DH_REQUEST_ERROR)
|
||||||
return 'error', DH_REQUEST_ERROR
|
return 'error', DH_REQUEST_ERROR
|
||||||
|
|
@ -76,19 +84,36 @@ class DhClient:
|
||||||
# print_roundtrip(r)
|
# print_roundtrip(r)
|
||||||
if r.status_code == 200:
|
if r.status_code == 200:
|
||||||
ret = r.json()
|
ret = r.json()
|
||||||
if ret.get('code') == '27001007':
|
if ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]:
|
||||||
self.get_token() # 重新获取token
|
detail = '大华错误:' + \
|
||||||
self.request(url, method, params, json, timeout, file_path_rela, raise_exception)
|
'{}|{}{}{}'.format(str(ret['code']), ret.get('errMsg', ''),
|
||||||
else:
|
ret.get('desc', ''), str(ret.get('data', '')))
|
||||||
if ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]:
|
err_detail = dict(detail=detail, code='dh_'+str(ret['code']))
|
||||||
detail = '大华错误:' + \
|
self.handle_log(result='fail', response=ret)
|
||||||
'{}|{}{}{}'.format(str(ret['code']), ret.get('errMsg', ''),
|
if raise_exception:
|
||||||
ret.get('desc', ''), str(ret.get('data', '')))
|
raise ParseError(**err_detail)
|
||||||
err_detail = dict(detail=detail, code='dh_'+str(ret['code']))
|
return 'fail', dict(detail=detail, code='dh_'+str(ret['code']))
|
||||||
if raise_exception:
|
self.handle_log(result='success', response=ret)
|
||||||
raise ParseError(**err_detail)
|
return 'success', ret['data'] if 'data' in ret else None
|
||||||
return 'fail', dict(detail=detail, code='dh_'+str(ret['code']))
|
|
||||||
return 'success', ret['data'] if 'data' in ret else None
|
self.handle_log(result='error', response=None)
|
||||||
if raise_exception:
|
if raise_exception:
|
||||||
raise APIException(**DH_REQUEST_ERROR)
|
raise APIException(**DH_REQUEST_ERROR)
|
||||||
return 'error', DH_REQUEST_ERROR
|
return 'error', DH_REQUEST_ERROR
|
||||||
|
|
||||||
|
def _get_response_ms(self):
|
||||||
|
"""
|
||||||
|
Get the duration of the request response cycle is milliseconds.
|
||||||
|
In case of negative duration 0 is returned.
|
||||||
|
"""
|
||||||
|
response_timedelta = now() - self.log["requested_at"]
|
||||||
|
response_ms = int(response_timedelta.total_seconds() * 1000)
|
||||||
|
return max(response_ms, 0)
|
||||||
|
|
||||||
|
def handle_log(self, result, response=None):
|
||||||
|
self.log.update({
|
||||||
|
"result": result,
|
||||||
|
"response": response,
|
||||||
|
"response_ms": self._get_response_ms()
|
||||||
|
})
|
||||||
|
Tlog(**self.log).save()
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
TAPI_CODE_WRONG = {"code": "tapi_code_wrong", "detail": "三方接口请求标识有误"}
|
||||||
|
XX_REQUEST_ERROR = {"code": "xx_request_error", "detail": "寻息接口访问异常"}
|
||||||
|
DH_REQUEST_ERROR = {"code": "dh_request_error", "detail": "大华接口访问异常"}
|
||||||
|
SP_REQUEST_ERROR = {"code": "sp_request_error", "detail": "音响接口访问异常"}
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
TAPI_CODE_WRONG = {"code": "tapi_code_wrong", "detail": "三方接口请求标识有误"}
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
# Generated by Django 3.2.12 on 2022-06-25 01:06
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('third', '0002_tdevice_is_clock'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Tlog',
|
||||||
|
fields=[
|
||||||
|
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
|
||||||
|
('target', models.CharField(max_length=20, verbose_name='请求目标')),
|
||||||
|
('result', models.CharField(max_length=20, verbose_name='请求结果')),
|
||||||
|
('path', models.CharField(help_text='请求地址', max_length=400)),
|
||||||
|
('requested_at', models.DateTimeField()),
|
||||||
|
('response_ms', models.PositiveIntegerField(default=0)),
|
||||||
|
('response', models.JSONField(blank=True, null=True)),
|
||||||
|
('method', models.CharField(max_length=10)),
|
||||||
|
('url', models.TextField(blank=True, null=True)),
|
||||||
|
('params', models.JSONField(blank=True, null=True)),
|
||||||
|
('body', models.JSONField(blank=True, null=True)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
@ -42,18 +42,17 @@ class TDevice(BaseModel):
|
||||||
null=False, blank=True)
|
null=False, blank=True)
|
||||||
|
|
||||||
|
|
||||||
class Tlog(BaseModel):
|
class Tlog(models.Model):
|
||||||
"""第三方请求与处理日志
|
"""第三方请求与处理日志
|
||||||
"""
|
"""
|
||||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
|
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
|
||||||
result_type = models.PositiveSmallIntegerField('结果类型',
|
target = models.CharField('请求目标', max_length=20)
|
||||||
default=10,
|
result = models.CharField('请求结果', max_length=20)
|
||||||
help_text='10成功20失败30错误')
|
path = models.CharField(max_length=400, help_text="请求地址")
|
||||||
result = models.JSONField(null=True, blank=True)
|
requested_at = models.DateTimeField()
|
||||||
request_method = models.CharField(max_length=10)
|
response_ms = models.PositiveIntegerField(default=0)
|
||||||
request_url = models.TextField(null=True, blank=True)
|
response = models.JSONField(null=True, blank=True)
|
||||||
request_params = models.JSONField(null=True, blank=True)
|
method = models.CharField(max_length=10)
|
||||||
request_json = models.JSONField(null=True, blank=True)
|
url = models.TextField(null=True, blank=True)
|
||||||
bind_my_request = models.CharField('关联用户请求ID',
|
params = models.JSONField(null=True, blank=True)
|
||||||
max_length=50,
|
body = models.JSONField(null=True, blank=True)
|
||||||
null=True, blank=True)
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import requests
|
||||||
from rest_framework.exceptions import APIException, ParseError
|
from rest_framework.exceptions import APIException, ParseError
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
from apps.utils.errors import SP_REQUEST_ERROR
|
from apps.third.errors import SP_REQUEST_ERROR
|
||||||
from apps.utils.tools import print_roundtrip
|
from apps.utils.tools import print_roundtrip
|
||||||
|
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
|
|
@ -3,7 +3,7 @@ from rest_framework.exceptions import ParseError, APIException
|
||||||
from apps.ecm.service import EcmService
|
from apps.ecm.service import EcmService
|
||||||
from apps.hrm.services import HrmService
|
from apps.hrm.services import HrmService
|
||||||
from apps.third.tapis import dhapis, xxapis, spapis
|
from apps.third.tapis import dhapis, xxapis, spapis
|
||||||
from apps.third.erros import TAPI_CODE_WRONG
|
from apps.third.errors import TAPI_CODE_WRONG
|
||||||
from apps.third.clients import dhClient, spClient, xxClient
|
from apps.third.clients import dhClient, spClient, xxClient
|
||||||
from apps.utils.mixins import MyLoggingMixin
|
from apps.utils.mixins import MyLoggingMixin
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
import time
|
import time
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
import uuid
|
||||||
import requests
|
import requests
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from rest_framework.exceptions import APIException, ParseError
|
from rest_framework.exceptions import APIException, ParseError
|
||||||
|
|
||||||
from apps.utils.errors import XX_REQUEST_ERROR
|
from apps.third.errors import XX_REQUEST_ERROR
|
||||||
|
from apps.third.models import Tlog
|
||||||
from apps.utils.tools import print_roundtrip
|
from apps.utils.tools import print_roundtrip
|
||||||
|
from django.utils.timezone import now
|
||||||
|
|
||||||
requests.packages.urllib3.disable_warnings()
|
requests.packages.urllib3.disable_warnings()
|
||||||
|
|
||||||
|
|
@ -23,6 +25,7 @@ class XxClient:
|
||||||
self.isGetingToken = False
|
self.isGetingToken = False
|
||||||
self.isRuning = True
|
self.isRuning = True
|
||||||
self.token = ''
|
self.token = ''
|
||||||
|
self.log = {}
|
||||||
self.t = None
|
self.t = None
|
||||||
self.setup()
|
self.setup()
|
||||||
|
|
||||||
|
|
@ -65,6 +68,8 @@ class XxClient:
|
||||||
params['accessToken'] = self.token
|
params['accessToken'] = self.token
|
||||||
json['username'] = self.username
|
json['username'] = self.username
|
||||||
json['buildId'] = settings.XX_BUILDID
|
json['buildId'] = settings.XX_BUILDID
|
||||||
|
self.log = {"requested_at": now(), "id": uuid.uuid4(), "path": url, "method": method,
|
||||||
|
"params": params, "body": json, "target": "xunxi", "result": 10}
|
||||||
if self.isGetingToken:
|
if self.isGetingToken:
|
||||||
req_num = 0
|
req_num = 0
|
||||||
while True:
|
while True:
|
||||||
|
|
@ -87,10 +92,30 @@ class XxClient:
|
||||||
if ret['errorCode'] != 0:
|
if ret['errorCode'] != 0:
|
||||||
err_detail = dict(detail='寻息错误:' + '|'.join(ret['errorMsg']),
|
err_detail = dict(detail='寻息错误:' + '|'.join(ret['errorMsg']),
|
||||||
code='xx_' + str(ret['errorCode']))
|
code='xx_' + str(ret['errorCode']))
|
||||||
|
self.handle_log(result='fail', response=None)
|
||||||
if raise_exception:
|
if raise_exception:
|
||||||
raise ParseError(**err_detail)
|
raise ParseError(**err_detail)
|
||||||
return 'fail', err_detail
|
return 'fail', err_detail
|
||||||
|
self.handle_log(result='success', response=None)
|
||||||
return 'success', ret['data']
|
return 'success', ret['data']
|
||||||
|
self.handle_log(result='error', response=None)
|
||||||
if raise_exception:
|
if raise_exception:
|
||||||
raise APIException(**XX_REQUEST_ERROR)
|
raise APIException(**XX_REQUEST_ERROR)
|
||||||
return 'error', XX_REQUEST_ERROR
|
return 'error', XX_REQUEST_ERROR
|
||||||
|
|
||||||
|
def _get_response_ms(self):
|
||||||
|
"""
|
||||||
|
Get the duration of the request response cycle is milliseconds.
|
||||||
|
In case of negative duration 0 is returned.
|
||||||
|
"""
|
||||||
|
response_timedelta = now() - self.log["requested_at"]
|
||||||
|
response_ms = int(response_timedelta.total_seconds() * 1000)
|
||||||
|
return max(response_ms, 0)
|
||||||
|
|
||||||
|
def handle_log(self, result, response=None):
|
||||||
|
self.log.update({
|
||||||
|
"result": result,
|
||||||
|
"response": response,
|
||||||
|
"response_ms": self._get_response_ms()
|
||||||
|
})
|
||||||
|
Tlog(**self.log).save()
|
||||||
|
|
@ -1,5 +1,2 @@
|
||||||
XX_REQUEST_ERROR = {"code": "xx_request_error", "detail": "寻息接口访问异常"}
|
|
||||||
DH_REQUEST_ERROR = {"code": "dh_request_error", "detail": "大华接口访问异常"}
|
|
||||||
SP_REQUEST_ERROR = {"code": "sp_request_error", "detail": "音响接口访问异常"}
|
|
||||||
SIGN_MAKE_FAIL = {"code": "sign_make_fail", "detail": "签名照生成失败,请重新上传"}
|
SIGN_MAKE_FAIL = {"code": "sign_make_fail", "detail": "签名照生成失败,请重新上传"}
|
||||||
PKS_ERROR = {"code": "pks_error", "detail": "未获取到主键列表"}
|
PKS_ERROR = {"code": "pks_error", "detail": "未获取到主键列表"}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue