格式化来自 Eve 接口的 GET 请求



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

现在,对于以下命令:

curl -g http://xxx.xxx.xxx.xx:xxxx/people?where={%22first_name%22:%20%22myself%22} -o "C:\UsersxxxDesktopoutput.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 字符串而不是保存 GET 请求中的整个"项目、id、文件"等?

您可以使用

urllib(或 Python2 的urllib2(来获取响应; 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:\UsersxxxDesktopoutput.txt', 'w') as f:
    f.write(data)

最新更新