从Eve界面格式化GET请求

时间:2018-01-28 15:15:21

标签: python mongodb rest curl eve

我在我的mongodb实例上使用Eve作为REST接口。 我想只保存特定字段的输出,而不是整个有效负载。

现在,对于以下命令:

curl -g http://xxx.xxx.xxx.xx:xxxx/people?where={%22first_name%22:%20%22myself%22} -o "C:\\Users\xxx\Desktop\output.txt"

我将输出保存到output.txt文件,它看起来像这样:

{"_items": [{"_id": "5a5f753e24b8bd18d4d28593", "file": "BASE64STRING", _updated": "Wed, 17 Jan 2018 16:09:34 GMT", "_created": "Wed, 17 Jan 2018 16:09:34 GMT", "_etag": "f38ef69eda077456da63ce8246a1d6665413f1cb"}]}

其中BASE64字符串是我从数据库中检索到的图像。 如何只保存BASE64字符串而不是保存整个"项目,id,文件"来自GET请求的其他?

1 个答案:

答案 0 :(得分:1)

您可以使用urllib(或urllib2获取Python2)来获取响应; urllib是python的默认库,用于访问互联网资源 然后,您可以使用json处理回复内容,选择"文件"项目,并保存到文件。

import urllib.request 
import json

url = 'http://xxx.xxx.xxx.xx:xxxx/people?where={"first_name": "myself"}'
r = urllib.request.urlopen(url)
j = json.loads(r.read().decode())
data = j['_items'][0]['file']

with open('C:\\Users\xxx\Desktop\output.txt', 'w') as f:
    f.write(data)