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

时间:2015-01-21 14:34:47

标签: 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)

这是我得到的输出

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

--------------
{u'id': u'6476edfa1d262ad81181d992da78149d', u'filename': u'image.jpg'}

1 个答案:

答案 0 :(得分:11)

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

data = r.json()

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

data['uploaded'][0]['id']

将索引硬编码到[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)

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