Python 请求 - 从 response.text 中提取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28069753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python requests - extracting data from response.text
提问by QweryBot
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.
我已经环顾了几天,无法弄清楚这一点。基本上,我将图像上传到服务器并获得一个 ID 作为回报,问题是我无法弄清楚如何提取此 ID 并将其更改为准备保存到数据库中的字符串。
Program Code
程序代码
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)
And here is the output I get
这是我得到的输出
<Response [200]>
{
"status": "success",
"uploaded": [
{
"filename": "image.jpg",
"id": "6476edfa1d262ad81181d992da78149d"
}
]
}
--------------
{u'id': u'6476edfa1d262ad81181d992da78149d', u'filename': u'image.jpg'}
采纳答案by Martijn Pieters
You are receiving JSON; you already use the response.json()
method to decode that to a Python structure:
您正在接收 JSON;您已经使用该response.json()
方法将其解码为 Python 结构:
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']
视为任何其他 Python 列表;内容只是一个字典,所以另一个字典键来获取id
值:
data['uploaded'][0]['id']
It is safe to hardcode the index to [0]
here as you know how many images you uploaded.
将索引硬编码到[0]
此处是安全的,因为您知道上传了多少图像。
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.
或者你可以处理data['status']
;这一切都取决于您在此处使用的 API 的确切语义。