python - 在 Python 3 中从服务器返回回复时引发 BadStatusLine 异常

标签 python python-3.x google-search-appliance

我正在尝试将一个脚本移植到 python 3,该脚本提交在这里找到的 XML 提要:

https://developers.google.com/search-appliance/documentation/files/pushfeed_client.py.txt

在运行 2to3.py 并进行一些小的调整以消除任何语法错误后,脚本失败并显示以下内容:

(py33dev) d:\dev\workspace>python pushfeed_client.py --datasource="TEST1" --feedtype="full" --url="http://gsa:19900/xmlfeed" --xmlfilename="test.xml"
Traceback (most recent call last):
  File "pushfeed_client.py", line 108, in <module>
    main(sys.argv)
  File "pushfeed_client.py", line 56, in main
    result = urllib.request.urlopen(request_url)
  File "C:\Python33\Lib\urllib\request.py", line 156, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python33\Lib\urllib\request.py", line 469, in open
    response = self._open(req, data)
  File "C:\Python33\Lib\urllib\request.py", line 487, in _open
    '_open', req)
  File "C:\Python33\Lib\urllib\request.py", line 447, in _call_chain
    result = func(*args)
  File "C:\Python33\Lib\urllib\request.py", line 1268, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Python33\Lib\urllib\request.py", line 1253, in do_open
    r = h.getresponse()
  File "C:\Python33\Lib\http\client.py", line 1147, in getresponse
    response.begin()
  File "C:\Python33\Lib\http\client.py", line 358, in begin
    version, status, reason = self._read_status()
  File "C:\Python33\Lib\http\client.py", line 340, in _read_status
    raise BadStatusLine(line)
http.client.BadStatusLine: <!DOCTYPE html>

为什么在服务器的响应中返回异常?这是我嗅探 session 时 GSA 的完整响应:

<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 400 (Bad Request)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}
  </style>
  <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>
  <p><b>400.</b> <ins>That’s an error.</ins>
  <p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>

它确实返回了一个 HTTP 400。只要 XML 负载中有一个 utf-8 字符,我就可以可靠地导致这个问题。当它是普通的 ascii 时,它可以完美地工作。这是我可以用来可靠地重现问题的最基本的代码版本:

import http.client
http.client.HTTPConnection.debuglevel = 1
with open("GSA_full_Feed.xml", encoding='utf-8') as xdata:
    payload = xdata.read()
content_length = len(payload)
feed_path = "xmlfeed"
content_type = "multipart/form-data; boundary=----------boundary_of_feed_data$"
headers = {"Content-type": content_type, "Content-length": content_length}
conn = http.client.HTTPConnection("gsa", 19900)
conn.request("POST", feed_path, body=payload.encode("utf-8"), headers=headers)
res = conn.getresponse()
print(res.read())
conn.close()

下面是一个用于引发异常的示例 XML 负载:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "gsafeed.dtd">
<gsafeed>
  <header>
    <datasource>TEST1</datasource>
    <feedtype>full</feedtype>
  </header>
  <group>
    <record action="add" mimetype="text/html" url="https://myschweetassurl.com">
      <metadata>
        <meta content="shit happens, then you die" name="description"/>
      </metadata>
      <content>wacky Umläut test of non utf-8 characters</content>
    </record>
  </group>
</gsafeed>

我能在第 2 和第 3 版本之间找到的唯一差异是每个请求的内容长度 header 。 Python 3 版本始终比 2 版本短,870 对 873。

最佳答案

经过大量的 wiresharking,我找出了问题的原因和解决方案,即内容长度 header 的设置方式。在脚本的 Python 3 端口中,我复制了设置内容长度的方法。这是哪个:

headers['Content-length']=str(len(body))

这是不正确的!正确的方法是这样的:

headers['Content-length']=str(len(bytes(body, 'utf-8')))

因为有效载荷必须是字节对象。当您对其进行字节编码时,长度与字符串版本不同。

return urllib.request.Request(theurl, bytes(body, 'utf-8'), headers)

当使用从 http.client.HTTPConnection 派生的任何内容时,您可以安全地省略手动设置内容长度 header 。它有一个检查内容长度 header 的内部方法,如果缺少,则根据内容主体的长度设置它,而不考虑形式。

问题是 Python 2 和 3 之间的翻译但细微差别以及它如何处理字符串和编码它们。正常的 ASCII 版本可以工作而 utf-8 版本不能工作,这一定是某种侥幸,哦,好吧。

关于python - 在 Python 3 中从服务器返回回复时引发 BadStatusLine 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297408/

相关文章:

python - 只读取包含大量列的大型文本数据文件的最后一列

python - 以 PEP8 方式检查 pandas 重复项

python - 在 python 中比较日期,== 有效但 <= 产生错误

python - 删除停用词/标点符号,标记并应用 Counter()

jquery - GSA 搜索建议使用 ss.js 或 Ajax 自动完成 jQuery 插件

css - 如何修复 Google Search Console 中的问题 "Clickable elements too close together"

performance - Google Search Appliances 与 Microsoft Enterprise Search (FAST)

python - 编辑组合框时拦截事件

python - 按列值将数据框拆分为 Excel 文件

python - 将 MS Azure 上麦克风的连续语音识别存储到单独的变量