python - 为什么在 python 日志记录 HTTPHandler 中需要 h.getresponse()?
问题描述
我重写了 python logging httphandler 的方法emit
以使其适应我的需要,我注意到了这一行
h.getresponse() #can't do anything with the result
- 为什么这条线是必要的?
我注意到在使用不安全日志记录时删除此行没有任何效果,但在使用安全连接时会导致日志失败。
def emit(self, record):
"""
Emit a record.
Send the record to the Web server as a percent-encoded dictionary
"""
try:
import http.client, urllib.parse
host = self.host
if self.secure:
h = http.client.HTTPSConnection(host, context=self.context)
else:
h = http.client.HTTPConnection(host)
url = self.url
data = urllib.parse.urlencode(self.mapLogRecord(record))
if self.method == "GET":
if (url.find('?') >= 0):
sep = '&'
else:
sep = '?'
url = url + "%c%s" % (sep, data)
h.putrequest(self.method, url)
# support multiple hosts on one IP address...
# need to strip optional :port from host, if present
i = host.find(":")
if i >= 0:
host = host[:i]
# See issue #30904: putrequest call above already adds this header
# on Python 3.x.
# h.putheader("Host", host)
if self.method == "POST":
h.putheader("Content-type",
"application/x-www-form-urlencoded")
h.putheader("Content-length", str(len(data)))
if self.credentials:
import base64
s = ('%s:%s' % self.credentials).encode('utf-8')
s = 'Basic ' + base64.b64encode(s).strip().decode('ascii')
h.putheader('Authorization', s)
h.endheaders()
if self.method == "POST":
h.send(data.encode('utf-8'))
h.getresponse() #can't do anything with the result
except Exception:
self.handleError(record)
解决方案
该getresponse()
调用通过获取对请求的响应来保证请求实际发送到服务器。
推荐阅读
- sql - PIVOT 查询多重加入
- angular - Electron + Angular Application + 错误:未捕获(承诺):错误:无法匹配任何路由。网址段:
- .net-core - 服务启动失败。验证您是否有足够的权限来启动系统服务
- javascript - 为什么 S3 文件上传后有前缀?
- makefile - 驱动程序未编译“没有规则来制作目标”
- reactjs - 如何通过按钮清除reactjs中的传单地图?
- tensorflow - 使用 tf.keras.preprocessing.image_dataset_from_directory() 时如何在预测期间获取文件名?
- python - 无法将该列更新为从 perforce 签出的 excel 文件
- android - 如何在约束布局中动态更改 android:layout_below?
- r - R:聚合(来自 stats v3.6.2)无法正常工作