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