【问题标题】:How to get only a subset of data using graphql?如何使用graphql仅获取数据子集?
【发布时间】:2019-08-12 21:13:48
【问题描述】:

我对 github API 有一个冗长的查询:

query = """
{
  repository(name: "fifteen5", owner: "15five") {
    commit: object(expression: "c63a83caf81ef21616392fe5acb84f9655f94d92") {
      ... on Commit {
        associatedPullRequests(first:5){
          edges{
            node{
              title
              number
              body
            }
          }
        }
      }
    }
  }
}

返回的值是一个深度嵌套的字典——要获得我想要的值(标题、数字和正文),我必须这样做:

# barf!
prs = areplStore['data']['repository']['commit']['associatedPullRequests']['edges']
for pr in prs:
    print(pr['node'])

那个字典访问的长度让我的眼睛流血了。我可以在我的 graphql 查询中指定什么来仅返回边缘结果吗?

【问题讨论】:

    标签: python graphql


    【解决方案1】:

    一种看起来稍微干净的方法是使用py-jsonq。不幸的是,这仍然需要很长时间。

    from pyjsonq import JsonQ
    
    j = JsonQ(data={'data': 
      {'repository': 
        {'commit': 
          {'associatedPullRequests': 
            {'edges': 
              [
                {'node': 
                  {
                    'title': 'Add more foobar', 
                    'number': 14253,
                    'body': 'More foo for the win'
                  }
                }
              ]
            }
          }
        }
      }
    }
    )
    
    prs = [
      edge['node'] for edge in j.at('data.repository.commit.associatedPullRequests.edges').get()
    ]
    
    print(prs)
    

    https://repl.it/@almenon/json-q-test

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 2022-11-30
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多