我有两个 Python 脚本。一种使用 Urllib2 库,一种使用 Requests 库。
我发现 Requests 更容易实现,但我找不到 urlib2 的 read()
函数的等效项。例如:
...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data
一旦我建立了我的帖子网址, data = response.read()
会给我内容 - 我正在尝试连接到 vcloud director api 实例,并且响应显示我可以访问的端点。但是,如果我按如下方式使用请求库…..
....
def post_call(username, org, password, key, secret):
endpoint = '<URL ENDPOINT>'
post_url = endpoint + 'sessions'
get_url = endpoint + 'org'
headers = {'Accept':'application/*+xml;version=5.1', \
'Authorization':'Basic '+ base64.b64encode(username + "@" + org + ":" + password), \
'x-id-sec':base64.b64encode(key + ":" + secret)}
print headers
post_call = requests.post(post_url, data=None, headers = headers)
print post_call, "POST call"
print post_call.text, "TEXT"
print post_call.content, "CONTENT"
post_call.status_code, "STATUS CODE"
....
…. print post_call.text
和 print post_call.content
不返回任何内容,即使请求后调用中的状态代码等于 200。
为什么我对 Requests 的响应没有返回任何文本或内容?
原文由 Oli 发布,翻译遵循 CC BY-SA 4.0 许可协议
Requests 没有相当于 Urlib2 的
read()
。看起来您发出的 POST 请求没有返回任何内容。这通常是 POST 请求的情况。也许它设置了一个cookie?状态码告诉你 POST 毕竟成功了。
为 Python 3 编辑:
Python 现在以不同的方式处理数据类型。
response.content
returns a sequence ofbytes
(integers that represent ASCII) whileresponse.text
is astring
(sequence of chars).因此,