从 Eve 接口格式化 GET 请求

Formatting GET request from Eve interface

我在 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 字符串而不是从 GET 请求中保存整个 "items,id,file" 等?

您可以使用urllib(或urllib2 for Python2)来获取响应; urllib 是 python 访问 Internet 资源的默认库。
然后可以用json、select、"file"项处理响应内容,并保存到文件中。

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)