如何读取Python请求的响应?

如何读取Python请求的响应?,python,python-requests,Python,Python Requests,我有两个Python脚本。一个使用,一个使用 我发现请求更容易实现,但我找不到urlib2的read()函数的等效函数。例如: ... response = url.urlopen(req) print response.geturl() print response.getcode() data = response.read() print data 一旦我建立了我的帖子url,data=response.read()为我提供了内容-我正在尝试连接到vcloud director api实

我有两个Python脚本。一个使用,一个使用

我发现请求更容易实现,但我找不到urlib2的
read()
函数的等效函数。例如:

...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data
一旦我建立了我的帖子url,
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"

....
。。。。
def post_呼叫(用户名、组织、密码、密钥、密码):
端点=“”
post_url=端点+“会话”
get_url=endpoint+'org'
headers={'Accept':'application/*+xml;version=5.1'\
“授权”:“基本”+base64.b64编码(用户名+“@”+org+”:“+密码)\
“x-id-sec”:base64.b64encode(key+”:“+secret)}
打印标题
post\u call=requests.post(post\u url,data=None,headers=headers)
打印post_呼叫,“post呼叫”
打印post_call.text,“text”
打印post_call.content,“content”
post_call.status_代码,“状态代码”
....
...
print post_call.text
print post_call.content
不返回任何内容,即使请求post call中的状态代码等于200


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

请求没有与Urlib2的
read()等效的文本或内容


如果响应是json格式的,则可以执行类似(python3)的操作:


要查看响应中的所有内容,可以使用
。\uuuu dict\uuuu

print(response.__dict__)

例如,如果将图像推送到某个API并希望返回结果地址(响应),则可以执行以下操作:

import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)

您知道应该从URL获得哪种类型的响应吗?Json、xml等?您从urllib2得到的响应是什么?POST请求可能返回重定向响应。检查响应标题:
post_call.headers
ok-谢谢。也许我在什么地方弄糊涂了。urllib2向我显示内容,因此我需要了解我做错了什么,以及两个库之间的不同调用。在某个端点,我希望读取请求,但无法使用requests.get(“url”)。此外,它需要花费不合理的时间来执行。不提供参数也会抛出一个错误,表示需要1个参数。请检查响应代码。您可能得到的是超时,而不是2XX响应。这也解释了为什么需要这么长时间。完美的解决方案。你节省了我的时间。谢谢在Python3中,
response.content
是一个
Bytes
实例,而
response.text
str
,因此它们不再直接比较相等(而是解码
response.content
和正确编码应该返回
response.text
print(response.__dict__)
import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)