用python从一个表里读取数据转化为text_Python请求-从response.text中提取数据

本文介绍了一种从服务器响应中提取上传图片ID的方法,并将其转换为字符串以便保存到数据库的过程。通过使用Python的requests库进行HTTP请求,解析返回的JSON数据,最终获取到了所需的图片ID。
摘要由CSDN通过智能技术生成

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.

Program Code

url =

with open("image.jpg", "rb") as image_file:

files = {'file': image_file}

auth = ('', '')

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)

And here is the output I get

{

"status": "success",

"uploaded": [

{

"filename": "image.jpg",

"id": "6476edfa1d262ad81181d992da78149d"

}

]

}

--------------

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

解决方案

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

data = r.json()

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']

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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值