Django - 新式中间件process_response

时间:2017-11-16 21:32:23

标签: python django middleware

我在Django中使用新的中间件,出于某种原因,它永远不会进入'process_response'部分。如果我理解正确,它应该在

之后发生
response = self.get_response(request)
__call__函数中的

。但它永远不会超出该行的代码。可能是什么原因?

这是我的中间件的定义方式:

class GlobalThreadVarMiddleware(object):
_threadmap = {}

def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    self._threadmap[_thread.get_ident()] = {}
    self._threadmap[_thread.get_ident()]['data_manager'] = DataManager()

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.
    current_data_manager = self.get_current_data_manager()
    current_data_manager.trigger_events()
    del self._threadmap[_thread.get_ident()]['data_manager']

    return response

@classmethod
def get_current_data_manager(cls):
    return cls._threadmap[_thread.get_ident()]['data_manager'] 

我正在使用Django 1.10。这是settings.py中的MIDDLEWARE参数:

MIDDLEWARE = [

'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'workflows.api.middleware.ApiCsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

'workflows.api.middleware.ExceptionMiddleware',
'workflows.api.global_thread_variables_middleware.GlobalThreadVarMiddleware'
]

这是列表中的最后一个。

这是ExceptionMiddleware代码:

class ExceptionMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
    guid, code, error, data, error_status = ExceptionMiddleware.log_exception(request, exception)

    return JsonResponse(
        {
            "error_id": guid,
            "code": code,
            "message": error,
            "data": data
        },
        status=error_status
    )

@staticmethod
def log_exception(request, exception):
    guid = str(uuid.uuid4())
    error = code = data = error_status = None

    if isinstance(exception, FlowException):
        error = str(exception.message)
        code = exception.code
        data = str(exception.data)
        error_status = exception.code
    elif isinstance(exception, Exception):
        error = str(exception.args)
        code = 10001
        data = {'exception_type': str(type(exception))}
        error_status = status.HTTP_500_INTERNAL_SERVER_ERROR

    logging.getLogger(__name__).exception('error_id: ' + guid,
                                          {'request': request, 'error_data': data, 'error_code': code,
                                           'error_message': error})
    kwargs = {} #"exc": exception, "tb": exception.__traceback__, "value": error}
    if newrelic.agent.current_transaction() is None:
        app = newrelic.agent.application()
        if app.active is False:
            app.activate()
            newrelic.agent.register_application()
        kwargs["application"] = app
    newrelic.agent.record_exception(**kwargs)

    return guid, code, error, data, error_status

1 个答案:

答案 0 :(得分:0)

我不能发表评论,因为我名声不好。

在您编辑之前我已经看到了您的问题,其中包含与您的问题直接相关的ImportError。你修复了ImportError吗?

Django中的新中间件样式与宣传的一样。我已经多次实现了这种新风格,为了确保,我甚至通过一些修改来测试你的代码以使其正常工作,并且它一般没有任何问题。