requestRecord.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Time : 2021/9/22 17:08
  4. @Auth : Locky
  5. @File :requestRecord.py
  6. @IDE :PyCharm
  7. """
  8. import json
  9. import time
  10. from django.utils.deprecation import MiddlewareMixin
  11. from Ansjer.config import LOGGER
  12. from Model.models import RequestRecordModel
  13. class RequestRecordMiddleware(MiddlewareMixin):
  14. def process_request(self, request):
  15. request.start_time = time.time()
  16. def process_response(self, request, response):
  17. try:
  18. execute_time = time.time() - request.start_time
  19. method = request.method
  20. url = request.path
  21. # 获取请求参数并转为字符串
  22. if method == 'GET':
  23. parameter = json.dumps(request.GET.dict())
  24. elif method == 'POST':
  25. parameter = json.dumps(request.POST.dict())
  26. else:
  27. parameter = ''
  28. content = eval(str(response.content, 'utf-8')) # bytes 转为 dict
  29. # 排除状态码
  30. code = [0, 405]
  31. # 排除路径
  32. url_list = ['/cloudstorage/getsignsts']
  33. if not url in url_list:
  34. if 'result_code' in content:
  35. if not content['result_code'] in code:
  36. LOGGER.info('请求路径:{}, 请求方式:{}, 输入数据:{}, 输出数据:{}, 响应状态:{}'.format(url, method, parameter, content, response.status_code))
  37. elif 'code' in content:
  38. if not content['result_code'] in code:
  39. LOGGER.info('请求路径:{}, 请求方式:{}, 输入数据:{}, 输出数据:{}, 响应状态:{}'.format(url, method, parameter, content, response.status_code))
  40. if response.status_code == 500: # 处理没有捕获异常的情况
  41. request_record_data = {
  42. 'method': method,
  43. 'url': url,
  44. 'parameter': parameter,
  45. 'execute_time': execute_time,
  46. 'status_code': 500,
  47. 'reason_phrase': response.reason_phrase,
  48. }
  49. RequestRecordModel.objects.create(**request_record_data)
  50. elif response.content: # 处理捕获异常的情况
  51. # print('content: ', response.content)
  52. # content = eval(str(response.content, 'utf-8')) # bytes 转为 dict
  53. # logger = logging.getLogger('info')
  54. # logger.info('content: {}'.format(content))
  55. error_flag = False
  56. reason_phrase = ''
  57. if 'result_code' in content and (content['result_code'] == 500 or content['result_code'] == 474):
  58. reason_phrase = content['result']
  59. error_flag = True
  60. elif 'code' in content and content['code'] == 500: # ResponseObject.returntype == 'pc'
  61. reason_phrase = content['data']
  62. error_flag = True
  63. if error_flag:
  64. request_record_data = {
  65. 'method': method,
  66. 'url': url,
  67. 'parameter': parameter,
  68. 'execute_time': execute_time,
  69. 'status_code': 500,
  70. 'reason_phrase': reason_phrase,
  71. }
  72. RequestRecordModel.objects.create(**request_record_data)
  73. finally:
  74. return response