Python 请求 - 从 response.text 中提取数据
Python requests - extracting data from response.text
我已经四处寻找几天了,还是想不通。基本上我是将图像上传到服务器并在 return 中获取 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'}
您正在接收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 的确切语义。
我已经四处寻找几天了,还是想不通。基本上我是将图像上传到服务器并在 return 中获取 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'}
您正在接收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 的确切语义。