在调试会话期间,我试图在gunicorn级别记录POST数据,所以我定义了pre_request钩子。
def pre_request(worker, req):
if req.query.startswith('action') and req.method == 'POST':
print(req.body) # (1)
request = copy.deepcopy(req.body) # (2)
print(request.read().decode())
在我尝试第一种方法后,打印正文,释放执行后我收到此错误:
..lib/python3.8/site-packages/gunicorn/http/wsgi.py", line 229, in should_close
if self.status_code < 200 or self.status_code in (204, 304):
AttributeError: 'Response' object has no attribute 'status_code'.
I suppose this is because the body buffer is empty.
当我尝试第二种方法:复制 Deepbody 时,我遇到了另一个问题:
..lib/python3.8/socket.py", line 272, in __getstate__
raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
TypeError: cannot pickle 'socket' object
然后我查看了gunicorn源代码来看看这个body对象中有什么,但我仍然不清楚:
如何取消请求正文?
深层复制创建原始对象及其所有嵌套对象的独立副本。它使套接字对象包含 Body 导致 pickle 无法序列化(套接字类型超出支持类型)。
你可以尝试:
def pre_request(worker, req):
body_data = copy.copy(req.body)
print(body_data.read().decode())
如果您的正文请求有文件数据,
utf-8
可能会在解码某些字符时出错。使用另一个,例如 latin-1