# -*- coding: utf-8 -*-
"""
@Time ： 2021/9/22 17:08
@Auth ： Locky
@File ：requestRecord.py
@IDE ：PyCharm
"""
import json
import logging
import time
from django.utils.deprecation import MiddlewareMixin
from Model.models import RequestRecordModel


class RequestRecordMiddleware(MiddlewareMixin):
    @staticmethod
    def process_request(request):
        request.start_time = time.time()

    @staticmethod
    def process_response(request, response):
        try:
            execute_time = time.time() - request.start_time
            method = request.method
            url = request.path

            if url != '/cloudstorage/getsignsts':
                # 获取请求参数并转为字符串
                if method == 'GET':
                    parameter = json.dumps(request.GET.dict())
                elif method == 'POST':
                    parameter = json.dumps(request.POST.dict())
                else:
                    parameter = ''
                content = eval(str(response.content, 'utf-8'))  # bytes 转为 dict

                # 记录响应码不为0的接口日志
                if ('result_code' in content and content['result_code'] != 0) or \
                        ('code' in content and content['code'] != 0):
                    logger = logging.getLogger('error_code')
                    logger.info('请求接口:{}, 请求方式:{}, 请求参数:{}, 响应数据:{}, 状态码:{}'.
                                format(url, method, parameter, content, response.status_code))

                else:
                    # Log responses with result_code or code equal to 0 to a different file 'error_code_0.log'
                    logger = logging.getLogger('success_code')
                    logger.info('请求接口:{}, 请求方式:{}, 请求参数:{}, 响应数据:{}, 状态码:{}'.
                                      format(url, method, parameter, content, response.status_code))

                if response.status_code == 500:  # 处理没有捕获异常的情况
                    request_record_data = {
                        'method': method,
                        'url': url,
                        'parameter': parameter,
                        'execute_time': execute_time,
                        'status_code': 500,
                        'reason_phrase': response.reason_phrase,
                    }
                    RequestRecordModel.objects.create(**request_record_data)
                elif response.content:  # 处理捕获异常的情况
                    error_flag = False
                    reason_phrase = ''
                    if 'result_code' in content and (content['result_code'] == 500 or content['result_code'] == 474):
                        reason_phrase = content['result']
                        error_flag = True
                    elif 'code' in content and content['code'] == 500:  # ResponseObject.returntype == 'pc'
                        reason_phrase = content['data']
                        error_flag = True
                    if error_flag:
                        request_record_data = {
                            'method': method,
                            'url': url,
                            'parameter': parameter,
                            'execute_time': execute_time,
                            'status_code': 500,
                            'reason_phrase': reason_phrase,
                        }
                        RequestRecordModel.objects.create(**request_record_data)
        finally:
            return response
