【问题标题】:Getting error while Formatting request query in Python在 Python 中格式化请求查询时出错
【发布时间】:2021-01-14 19:59:00
【问题描述】:

我正在尝试通过 python 请求 Graphql API。我已经编写了脚本,它试图从 Github 中为每个组织提取审计日志。

这是我写的 Python 脚本。

Query = """
query {
  organization(login: '{}') {
    auditLog(first: 100, '{}') {
      edges {
        node {
          ... on RepositoryAuditEntryData {
            repository {
              name
            }
          }
          ... on OrganizationAuditEntryData {
            organizationResourcePath
            organizationName
            organizationUrl
          }

          ... on TeamAuditEntryData {
            teamName
          }

          ... on TopicAuditEntryData {
            topicName
          }

          ... on OauthApplicationAuditEntryData {
            oauthApplicationName
          }
          
          ... on EnterpriseAuditEntryData {
            enterpriseResourcePath
            enterpriseUrl
            enterpriseSlug
          }

          ... on AuditEntry {
            actorResourcePath
            action
            actorIp
            actorLogin
            operationType
            createdAt
            actorLocation {
              countryCode
              country
              regionCode
              region
              city
            }
            #User 'Action' was performed on
            userLogin
            userResourcePath
            userUrl
          }
        }
        cursor
      }
      pageInfo {
        endCursor
        hasNextPage
        hasPreviousPage
      }
    }
  }
}
"""
  
l = []
l.append("CoreDevOpsTools") 
l.append("JIRA-Cloud")

res = []

for i in range(len(l)):   
    org = str(l[i])
    after = ''

    while True:
        result = requests.post('https://api.github.com/graphql',
                                json={'query': Query.format(org,after)},
                                headers=headers)

        json_data = json.loads(result.text)

        if 'errors' in json_data:
            print(json_data['errors'])
            break

        res_list = json_data['data']['organization']['auditLog']

        for items in res_list['edges']:
            res.append(items)

        if not res_list['pageInfo']['hasNextPage']:
            break

        after = 'after: "%s"' % res_list['edges'][-1]['cursor']
        time.sleep(1)

  File "../AuditLog.py", line 98, in <module>
    json={'query': Query.format(org,after)},
KeyError: '\n  organization(login'

这是 Insomnia/Postman 中查询的结构。

query {
  organization(login: "CoreDevOpsTools") {
    auditLog(first: 100, after: "XYZ") {
      edges {
        node {
          ... on RepositoryAuditEntryData {
            repository {
              name
            }
          }
          ... on OrganizationAuditEntryData {
            organizationResourcePath
            organizationName
            organizationUrl
          }

          ... on TeamAuditEntryData {
            teamName
          }

          ... on TopicAuditEntryData {
            topicName
          }

          ... on OauthApplicationAuditEntryData {
            oauthApplicationName
          }
          
          ... on EnterpriseAuditEntryData {
            enterpriseResourcePath
            enterpriseUrl
            enterpriseSlug
          }

          ... on AuditEntry {
            actorResourcePath
            action
            actorIp
            actorLogin
            operationType
            createdAt
            actorLocation {
              countryCode
              country
              regionCode
              region
              city
            }
            #User 'Action' was performed on
            userLogin
            userResourcePath
            userUrl
          }
        }
        cursor
      }
      pageInfo {
        endCursor
        hasNextPage
        hasPreviousPage
      }
    }
  }
}

这是我遇到的错误,我无法弄清楚出了什么问题。我在这里查看了其他相同类型的问题,但也没有用。

【问题讨论】:

    标签: python python-3.x string graphql format


    【解决方案1】:

    您的代码的问题是您尝试格式化的字符串在您不想替换的地方有大括号。例如第一行“查询{”

    您可以通过加倍大括号来解决此问题。所以“{”变成“{{”等等。 更多信息在这里:stackoverflow.com

    【讨论】:

    • ``` query{{ organization(login: '{}') {{ }} }} ```据我了解,这就是我必须写的,对吧?跨度>
    • @KishanKumarGupta 是的!或者,如果您认为它看起来不太好,您也可以尝试这个答案:link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2020-07-24
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多