确定Python2和Python3之间http请求的差异



我正在尝试使用Python3向托管石墨发送指标。网站上给出的示例是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)请求实际发送的内容,是否有任何建议?

不要混合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查看请求

最新更新