Python GraphQLAPI调用组合

2024-06-16 08:46:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习如何使用python,但在使用GraphQLAPI调用时遇到了一些问题

我正试图建立一个循环,使用分页来获取所有信息,我的第一个请求工作正常

values = """
      {"query" : "{organizations(ids:) {pipes {id name phases {id name cards_count cards(first:30){pageInfo{endCursor hasNextPage} edges {node {id title current_phase{name} assignees {name} due_date createdAt finished_at fields{name value filled_at updated_at} } } } } }}}"}
    """

但是,第二个使用结束游标作为变量的调用对我不起作用。我假设这是因为我不理解如何正确地转义变量的字符串。但就我的一生而言,我无法理解该怎么做

这是我到目前为止得到的

values = """
      {"query" : "{phase(id: """ + phaseID+ """ ){id name cards_count cards(first:30, after:"""\" + pointer + "\"""){pageInfo{endCursor hasNextPage} edges {node {id title assignees {name} due_date createdAt finished_at fields{name value datetime_value updated_at phase_field { id label }  } } } } } }"}
        """ 

第二个循环只返回400个错误请求

任何帮助都将不胜感激


Tags: nameidnodevaluecountqueryatfirst
2条回答

一般来说,您应该避免像这样使用字符串操作来构建查询

在GraphQL查询本身中,GraphQL允许variables作为查询中的占位符,用于稍后插入的值。您需要在查询顶部声明变量,然后可以在查询中的任何位置引用它们。没有JSON包装器的查询本身看起来像

query = """
  query MoreCards($phase: ID!, $cursor: String) {
    phase(id: $phase) {
      id, name, cards_count
      cards(first: 30, after: $cursor) {
        ... CardConnectionData
      }
    }
  }
"""

为了实际提供变量值,它们作为普通字典传递

variables = {
  "phase": phaseID,
  "cursor": pointer
}

实际的请求主体是a straightforward JSON structure。您也可以将其构造为字典:

body = {
  "query": query,
  "variables": variables
}

现在可以使用标准^{}模块将其格式化为字符串

print(json.dumps(body))

或者将它传递给^{}包之类的东西,它可以直接接受对象并为您编码

我有一个类似的情况,我必须通过从GraphQL端点分页来聚合数据。尝试上述解决方案对我没有那么好的效果

要启动graphql的头文件配置,如下所示:

 headers = {
        "Authorization":f"Bearer {token}",
        "Content-Type":"application/graphql"
}

对于我的查询字符串,我使用了带变量占位符的三重引号:

  user_query = 
   """
         {
           user(
                limit:100,
                page:$page,
                sort:[{field:"email",order:"ASC"}]
            ){
                list{
                    email, 
                    count
                 }
            }
   """

基本上,我在这里有我的页面循环:

for page in range(1, 9):
    formatted_query = user_query.replace("$page",f'{page}')
    response = requests.post(api_url, data=formatted_query, 
    headers=headers)
    status_code, json = response.status_code, response.json()

相关问题 更多 >