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

时间:2013-05-18 01:24:54

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

from base64 import b64encode

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

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

$ nc -l 8888

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