diff --git a/apps/third/speaker.py b/apps/third/speaker.py index eb8f4f3b..fac4c075 100644 --- a/apps/third/speaker.py +++ b/apps/third/speaker.py @@ -7,6 +7,7 @@ import logging import requests from rest_framework.exceptions import APIException, ParseError from django.conf import settings +from requests.exceptions import RequestException from apps.third.errors import SP_REQUEST_ERROR from apps.third.models import Tlog @@ -61,27 +62,29 @@ class SpClient: files = {'file': open(settings.BASE_DIR + file_path_rela, 'rb')} if params: url = url.format(**params) - r = getattr(requests, method)('{}{}'.format(settings.SP_BASE_URL, url), - headers=self.headers, params=params, json=json, - timeout=timeout, files=files, verify=False) - # if settings.DEBUG: - # print_roundtrip(r) - ret = r.text - if 300 > r.status_code >= 200: - ret = r.json() - if 'code' in ret and ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]: - detail = '音响错误:{}'.format(str(ret.get('msg', ''))) - err_detail = dict(detail=detail, code='sp_'+str(ret['code'])) - self.handle_log(result='fail', response=ret) - if raise_exception: - raise ParseError(**err_detail) - return 'fail', err_detail - # self.handle_log(result='success', response=ret) - return 'success', ret - self.handle_log(result='error', response=ret) - if raise_exception: - raise APIException(**SP_REQUEST_ERROR) - return 'error', SP_REQUEST_ERROR + try: + r = getattr(requests, method)('{}{}'.format(settings.SP_BASE_URL, url), + headers=self.headers, params=params, json=json, + timeout=timeout, files=files, verify=False) + # if settings.DEBUG: + # print_roundtrip(r) + ret = r.text + if 300 > r.status_code >= 200: + ret = r.json() + if 'code' in ret and ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]: + detail = '音响错误:{}'.format(str(ret.get('msg', ''))) + err_detail = dict(detail=detail, code='sp_'+str(ret['code'])) + self.handle_log(result='fail', response=ret) + if raise_exception: + raise ParseError(**err_detail) + return 'fail', err_detail + # self.handle_log(result='success', response=ret) + return 'success', ret + except RequestException: + self.handle_log(result='error', response=ret) + if raise_exception: + raise APIException(**SP_REQUEST_ERROR) + return 'error', SP_REQUEST_ERROR def speak(self, path: str, sns: list, v_num: int): """播放报警声