在Python中格式化请求查询时出错



我正在尝试通过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'

这是失眠/邮差中的查询结构。

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
}
}
}
}

这是我犯的错误,我不知道出了什么问题。我在这里看了其他同样类型的问题,但这也不起作用。

代码的问题是,您试图格式化的字符串本身在不想替换的地方有花括号。例如第一行";查询{〃

你可以通过加倍花括号来解决这个问题。所以"{〃变为{{〃等。点击此处了解更多信息:stackoverflow.com

最新更新