python - 为什么 python 日志记录 HTTPHandler 需要 h.getresponse() ?

标签 python logging httphandler

我重写了pythonlogging 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() 调用通过获取请求的响应来保证请求实际上发送到服务器。

关于python - 为什么 python 日志记录 HTTPHandler 需要 h.getresponse() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52465133/

相关文章:

python - Pandas 使用其他列中的值创建新列,并根据列值进行选择

java - 在 log4j 中,在记录之前检查 isDebugEnabled 是否会提高性能?

ruby - 如何将 Ruby Sequel 日志记录设置为 DEBUG 级别?

javascript - 如何将 .ashx 文件中的值返回到变量中的 javascript

asp.net-mvc - HttpHandler 永远不会被调用

python - 将 pandas 数据框列拆分为多个 bool 列

python - 具有指定(附加)列的 Pandas 数据透视

python - 如何使用 REST 在 Django 的完整系统测试中测试保存后、保存前

java - jboss 7 记录器将相同的数据写入两个不同的文件

javascript - 由 HttpHandler 生成的 JS 的安全性