0

我正在尝试使用 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)请求实际发送的内容有什么建议吗?

4

1 回答 1

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 查看请求。

于 2013-05-18T03:42:27.607 回答