Python请求-从response.text中提取数据
我已经环顾了几天,无法解决这个问题。基本上,我正在将图像上传到服务器并获得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'}
回答:
您正在接收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的确切语义。
以上是 Python请求-从response.text中提取数据 的全部内容, 来源链接: utcz.com/qa/433914.html

