如何阅读 Python 请求的响应?

新手上路,请多包涵

我有两个 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.textprint post_call.content 不返回任何内容,即使请求后调用中的状态代码等于 200。

为什么我对 Requests 的响应没有返回任何文本或内容?

原文由 Oli 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 348
1 个回答

Requests 没有相当于 Urlib2 的 read()

 >>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

看起来您发出的 POST 请求没有返回任何内容。这通常是 POST 请求的情况。也许它设置了一个cookie?状态码告诉你 POST 毕竟成功了。

为 Python 3 编辑:

Python 现在以不同的方式处理数据类型response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

因此,

 >>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

原文由 aychedee 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题