首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python请求-从response.text中提取数据

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

Stack Overflow用户
提问于 2015-01-21 22:34:47
回答 1查看 36K关注 0票数 9

我已经到处看了几天了,还是弄不明白这个问题。基本上,我上传一个图像到服务器并得到一个ID作为返回,问题是我不知道如何提取这个ID并将其更改为准备保存到数据库中的字符串。

程序代码

代码语言:javascript
复制
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)

这是我得到的输出

代码语言:javascript
复制
<Response [200]>
{
    "status": "success",
    "uploaded": [
        {
            "filename": "image.jpg",
            "id": "6476edfa1d262ad81181d992da78149d"
        }
     ]
}

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-21 22:36:01

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

代码语言:javascript
复制
data = r.json()

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

代码语言:javascript
复制
data['uploaded'][0]['id']

在这里将索引硬编码到[0]是安全的,因为你知道你上传了多少张图片。

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

代码语言:javascript
复制
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的确切语义。

票数 22
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28069753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档