gpt4 book ai didi

django - 我有一个中间件,我想在其中记录每个请求/响应。如何访问 POST 数据?

转载 作者:行者123 更新时间:2023-12-03 12:15:23 29 4
gpt4 key购买 nike

我有这个中间件

import logging

request_logger = logging.getLogger('api.request.logger')


class LoggingMiddleware(object):

def process_response(self, request, response):
request_logger.log(logging.DEBUG,
"GET: {}. POST: {} response code: {}. response "
"content: {}".format(request.GET, request.DATA,
response.status_code,
response.content))
return response

问题是 process_response 方法中的请求没有 .POST、.DATA 或 .body。我正在使用 django-rest-framework 并且我的请求具有 Content-Type: application/json

请注意,如果我将日志记录到 process_request 方法 - 它具有 .body 和我需要的一切。但是,我需要在单个日志条目中同时包含请求和响应。

最佳答案

这是我制作的完整解决方案

"""
Api middleware module
"""
import logging

request_logger = logging.getLogger('api.request.logger')


class LoggingMiddleware(object):
"""
Provides full logging of requests and responses
"""
_initial_http_body = None

def process_request(self, request):
self._initial_http_body = request.body # this requires because for some reasons there is no way to access request.body in the 'process_response' method.


def process_response(self, request, response):
"""
Adding request and response logging
"""
if request.path.startswith('/api/') and \
(request.method == "POST" and
request.META.get('CONTENT_TYPE') == 'application/json'
or request.method == "GET"):
request_logger.log(logging.DEBUG,
"GET: {}. body: {} response code: {}. "
"response "
"content: {}"
.format(request.GET, self._initial_http_body,
response.status_code,
response.content), extra={
'tags': {
'url': request.build_absolute_uri()
}
})
return response

注意,这
'tags': {
'url': request.build_absolute_uri()
}

将允许您在哨兵中按 url 过滤。

关于django - 我有一个中间件,我想在其中记录每个请求/响应。如何访问 POST 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24784985/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com