Python 请求 - 从 response.text 中提取数据 [英] Python requests - extracting data from response.text

查看:267
本文介绍了Python 请求 - 从 response.text 中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been looking around for a few days now and cannot figure this out. Basically I'm uploading an image to a server and get an ID in return, the problem is I cannot figure out how to extract this ID and change it into a String ready to be saved into a database.

程序代码

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 结构:

You are receiving JSON; you already use the response.json() method to decode that to a Python structure:

data = r.json()

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

You can treat data['uploaded'] as any other Python list; the content is just the one dictionary, so another dictionary key to get the id value:

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

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

It is safe to hardcode the index to [0] here as you know how many images you uploaded.

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

You could use exception handling to detect if anything unexpected was returned:

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 的确切语义.

or you could handle data['status']; it all depends on the exact semantics of the API you are using here.

这篇关于Python 请求 - 从 response.text 中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆