【问题标题】:Google API to get Snapshot using filter,Google API 使用过滤器获取快照,
【发布时间】:2018-12-20 19:10:30
【问题描述】:

我编写了以下代码,它返回给我的快照列表,其中有特定的字符串,但这不返回大小为 0 的快照,

https://cloud.google.com/compute/docs/reference/rest/v1/snapshots/list

this  API have following attributes:
  • project_id
  • 过滤器

我正在尝试放置一些基于正则表达式的过滤器 匹配名称中包含“intance-snap”的所有快照。

 def snapshotlist():  
        query = "name eq <string>.*"  
        snaplist = compute.snapshots().list(project=project,filter=query).execute()  
        snaplist = ast.literal_eval(json.dumps(snaplist))  
        for snap in snaplist['items']:  
            print(snap['name'])

上面的代码不返回大小为 0 的快照,有没有办法获取所有快照,不管 SIZE 吗?

【问题讨论】:

  • 从可选参数的过滤器属性的文档中,比较运算符必须是=!=&gt;&lt; 所以没有,您无法执行类似于使用 Drive API 所做的查询,例如q: "name contains 'some string'" 收集您的快照列表,然后使用您的语言的字符串和正则表达式方法过滤输出。
  • 您能否发表评论作为对问题的回答,以造福社区?
  • @tehhowch 你能再看看吗,我已经为此编写了代码,但它没有得到完整的结果。
  • query = "name eq cp.*" ,当我使用它时,我得到了响应的快照列表: cptest15305994871 cptest15305994872 cptest15305994873 cptest15305994873 cptest15305994875 cptest15305994876 cptest1530599481 cptest153059948159481
  • 那么问题是什么?你有结果,所以你的问题就解决了。

标签: python google-cloud-platform google-api-client snapshot


【解决方案1】:

Snapshot documentation,对于可选参数的filter属性:

表达式必须指定字段名称、比较运算符以及要用于过滤的值。该值必须是字符串、数字或布尔值。 比较运算符必须是=!=&gt;&lt;

虽然这意味着您无法执行类似于使用 Drive API 所做的查询,例如q: "name contains 'some string'"Snapshots#list 方法似乎仍然支持通配符匹配。如果您无法成功编写适当的正则表达式,那么解决方案是收集您的整个Snapshots 列表,然后使用您的语言的字符串和正则表达式方法过滤输出。

def get_matching_snapshots(projectId: str, query='',
                           fields='id,nextPageToken,warning,items(id,name,description)'):
    snaplist = []
    params = {project: projectId,
              filter: query,
              fields: fields}
    # Collect all pages of results
    request = compute.snapshots().list(**params)
    while request:
        response = request.execute()
        if 'items' in response:
            snaplist.extend(response['items'])
        if 'warning' in response:
            pprint(response['warning'])
        request = compute.snapshots().list_next(request, response)

    return snaplist

# Use 'filter' parameter to restrict on server side:
name_fragment = "some required part of the name"
q = f'name = "{name_fragment}.*"'
pprint(get_matching_snapshots("some project id", q))

# get all, then apply restrictions after retrieval:
all_snapshots = get_matching_snapshots("some project id")
matches = []
rgx = re.compile('some regex')
for snap in all_snapshots:
    # use rgx.match with the relevant snap property
    ...

您可能会发现查阅 Compute API 的 Python 文档或使用 Python 客户端的 API Explorer 会有所帮助:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2021-10-12
    • 2018-03-06
    • 1970-01-01
    相关资源
    最近更新 更多