KeyError:“ python3”中的“数据”

时间:2019-10-18 14:35:00

标签: json python-3.x graphql python-3.7

我正在使用graphql来显示用户发出的拉取请求的数量。当我在GitHub的graphql Explorer中运行查询时,查询工作正常。但是,当我运行脚本时,它显示KeyError并且期望值为字符串。即使输入的用户名已转换为字符串。

代码如下:

accessToken = "###################################"        
headers = {"Authorization": "bearer "+ accessToken }

    def getpullRequests(username):
        topic_query = """
        query {
        repositoryOwner(login:""" + str(username) + """) {
            login 
            ... on User {
            name
            avatarUrl
            pullRequests(last: 100){
                nodes{
                id
                createdAt
                additions
                deletions
                }
            }
            } 
        }
        } 
        """
        request = requests.post('https://api.github.com/graphql', json={'query': topic_query}, headers=headers)
        if request.status_code == 200:
            result = request.json()
            prsdata = {}
            for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
                prdata = {}
                if re.match(r'^2019-10', pr['createdAt']):
                    prdata['createdAt'] = pr['createdAt']
                    prdata['additions'] = pr['additions']
                    prdata['deletions'] = pr['deletions']
                    prsdata[pr['id']] = prdata
            if prsdata:
                print(prsdata)
            else:
                print("No PRs made in Hacktoberfest")

    if __name__ == "__main__":
        username = input("Enter the GitHub username: ")
        getpullRequests(username)

但是,在尝试了一些调试之后,我发现问题出在这行:

for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:

运行代码时,我遇到的错误是:

Enter the GitHub username: adiaux
Traceback (most recent call last):
  File "script.py", line 47, in <module>
    getpullRequests(username)
  File "script.py", line 33, in getpullRequests
    for pr in result['data']['repositoryOwner']['pullRequests']['nodes']:
KeyError: 'data'

请帮助:)

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 基本上,我使用了graphQL变量,并将变量变成了字典,就像这样:

 variables=dict({
        "name":str(username)
    })

但是我相应地通过以下方式修改了查询:

 query ($name:String!){
    repositoryOwner(login:$name){
        login 
        ... on User {
        name
        avatarUrl
        pullRequests(last: 100){
            nodes{
            id
            createdAt
            additions
            deletions
            }
        }
        } 
    }
    }

感谢尝试解决此问题的人:)