requestRecord.py 3.3 KB

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