Python请求 - 从response.text中提取数据

Qwe*_*Bot 4 python json python-requests

我现在已经环顾了几天,无法解决这个问题.基本上我是将图像上传到服务器并获得一个ID作为回报,问题是我无法弄清楚如何提取此ID并将其更改为准备保存到数据库中的String.

程序代码

url = <Server address>
with open("image.jpg", "rb") as image_file:
    files = {'file': image_file}
    auth = ('<Key>', '<Pass>')
    r = requests.post(url, files=files, auth=auth)

data = r.json()
uploaded = data.get('uploaded')
content_id = uploaded[0]


print r
print r.text
print '--------------'
print str(content_id)
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出

<Response [200]>
{
    "status": "success",
    "uploaded": [
        {
            "filename": "image.jpg",
            "id": "6476edfa1d262ad81181d992da78149d"
        }
     ]
}

--------------
{u'id': u'6476edfa1d262ad81181d992da78149d', u'filename': u'image.jpg'}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 12

您正在收到JSON; 您已经使用该response.json()方法将其解码为Python结构:

data = r.json()
Run Code Online (Sandbox Code Playgroud)

您可以data['uploaded']像任何其他Python列表一样对待; 内容只是一个字典,所以另一个字典键来获取id值:

data['uploaded'][0]['id']
Run Code Online (Sandbox Code Playgroud)

将索引硬编码到[0]此处是安全的,因为您知道上传了多少图像.

您可以使用异常处理来检测是否返回了任何意外情况:

try:
    image_id = data['uploaded'][0]['id']
except (IndexError, KeyError):
    # key or index is missing, handle an unexpected response
    log.error('Unexpected response after uploading image, got %r',
              data)
Run Code Online (Sandbox Code Playgroud)

或者你可以处理data['status']; 这一切都取决于您在此处使用的API的确切语义.