【问题标题】:Determine difference in http request between Python2 and Python3确定 Python2 和 Python3 之间 http 请求的差异
【发布时间】:2013-05-18 01:24:53
【问题描述】:

我正在尝试使用 Python3 将指标发送到 Hosted Graphite。网站上给出的示例是 Python2,我已经成功地将 TCP 和 UDP 示例移植到 Python3(尽管我没有经验,并且已经提交了示例以便可以更新文档),但是我无法获得 HTTP 方法工作。

Python2 示例如下所示:

import urllib2, base64

url = "https://hostedgraphite.com/api/v1/sink"
api_key = "YOUR-API-KEY"

request = urllib2.Request(url, "foo 1.2")
request.add_header("Authorization", "Basic %s" % base64.encodestring(api_key).strip())
result = urllib2.urlopen(request)

这成功了,返回一个 HTTP 200。

到目前为止,我已经将这么多移植到 Python3,虽然我(最终)能够让它发出有效的 HTTP 请求(即没有语法错误),但请求失败,返回 HTTP 400

import urllib.request, base64

url = "https://hostedgraphite.com/api/v1/sink"
api_key = b'YOUR-API-KEY'

metric = "testing.python3.http 1".encode('utf-8')
request = urllib.request.Request(url, metric)
request.add_header("Authorization", "Basic %s" % base64.encodestring(api_key).strip())
result = urllib.request.urlopen(request)

完整的结果是:

>>> result = urllib.request.urlopen(request)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 160, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 479, in open
    response = meth(req, response)
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 591, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 517, in error
    return self._call_chain(*args)
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 451, in _call_chain
    result = func(*args)
  File "/usr/local/Cellar/python3/3.3.1/Frameworks/Python.framework/Versions/3.3/lib/python3.3/urllib/request.py", line 599, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

我做错了什么很明显吗?关于如何捕获和比较成功(python2)和失败(python3)请求实际发送的内容有什么建议吗?

【问题讨论】:

  • 数据包嗅探器说...?
  • 更新结果为tcpdump
  • 不幸的是,数据包内容本身丢失了。

标签: http python-3.x http-headers python-2.x api-key


【解决方案1】:

不要混合 Unicode 字符串和字节:

>>> "abc %s" % b"def"
"abc b'def'"

您可以按如下方式构造标题:

from base64 import b64encode

headers = {'Authorization': b'Basic ' + b64encode(api_key)}

查看请求的快速方法是将 url 中的主机更改为 localhost:8888 并在发出请求之前运行:

$ nc -l 8888

您也可以使用 wireshark 来查看请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    相关资源
    最近更新 更多