如何使用graphql仅获取一部分数据?

时间:2019-03-21 22:30:25

标签: python graphql

我有一个冗长的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查询中指定某些内容以仅返回边缘结果吗?

1 个答案:

答案 0 :(得分:0)

一种看上去更简洁的方法是使用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