我已经到处看了几天了,还是弄不明白这个问题。基本上,我上传一个图像到服务器并得到一个ID作为返回,问题是我不知道如何提取这个ID并将其更改为准备保存到数据库中的字符串。
程序代码
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'}发布于 2015-01-21 22:36:01
您正在接收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的确切语义。
https://stackoverflow.com/questions/28069753
复制相似问题