如何从Python请求中读取响应?

Oli*_*Oli 45 python python-requests

我有两个Python脚本.一个使用Urllib2库,一个使用Requests库.

我发现Requests更容易实现,但我找不到urlib2 read()函数的等价物.例如:

...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data
Run Code Online (Sandbox Code Playgroud)

一旦我建立了我的帖子网址,data = response.read()给我内容 - 我正在尝试连接到vcloud导演api实例,响应显示我可以访问的端点.但是,如果我使用Requests库如下.....

....

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"

....
Run Code Online (Sandbox Code Playgroud)

....的print post_call.textprint post_call.content没有返回,即使状态码等于在请求后调用200.

为什么我的回复不会从请求中返回任何文本或内容?

ayc*_*dee 92

请求没有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
Run Code Online (Sandbox Code Playgroud)

看起来你正在发出的POST请求没有返回任何内容.POST请求通常就是这种情况.也许它设置了一个cookie?状态代码告诉您POST完全成功.

  • 好,谢谢.也许我在某个地方感到困惑.urllib2向我展示了内容,所以我需要了解我做错了什么以及两个库之间的不同调用. (2认同)
  • 在Python 3中,`response.content`是一个`Bytes`实例,`response.text`是`str`,因此它们将不再直接比较相等(但是使用正确的编码解码`response.content`应该返回`响应.文本` (2认同)

Jor*_*ega 37

如果响应在 json 中,您可以执行类似 (python3) 的操作:

import json
import requests as reqs

# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')

# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)

for i in response_dict:
    print("key: ", i, "val: ", response_dict[i])
Run Code Online (Sandbox Code Playgroud)

要查看响应中的所有内容,您可以使用.__dict__

print(response.__dict__)
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用这种方式“漂亮地打印”;打印(json.dumps(response_dict,缩进= 4,sort_keys = True)) (2认同)

Mar*_*lov 11

如果您将图像(例如图像)推送到某个 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)
Run Code Online (Sandbox Code Playgroud)


kwi*_*ick 7

如果 Response 是 Json 格式,则可以直接使用 Python3 中的以下方法,无需使用json importandjson.loads()方法:

response.json()
Run Code Online (Sandbox Code Playgroud)