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

查看:3762
本文介绍了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天全站免登陆