首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python模块graphqlclient将变量传递给GraphQL

使用python模块graphqlclient将变量传递给GraphQL
EN

Stack Overflow用户
提问于 2018-11-28 08:01:28
回答 1查看 226关注 0票数 1

我正在尝试从API + graphQL服务器获取一些数据。Here你可以看到这个方案。Here端点。我使用的是Python2.7.5,其中有一个名为graphqlclient的模块,这是我写的脚本:

代码语言:javascript
复制
from graphqlclient import GraphQLClient 
client = GraphQLClient('http://genetics-api.opentargets.io/graphql')
result = client.execute('''
query {
manhattan(
studyId: "GCST004599"
pageIndex: 0
pageSize: 10000
){associations
{variant {
rsId
altAllele
refAllele
nearestGene {
id}nearestCodingGene {
id}}pval
bestGenes{
gene {
id
}score}
credibleSetSize
ldSetSize
}}}''')
print(result)

到目前为止,它是有效的,我得到了我所期望的。但是,我也想为"studyID“使用一组不同的值,并且我不能设置变量。您有使用此模块的经验或任何其他建议吗?

EN

回答 1

Stack Overflow用户

发布于 2021-10-28 12:12:26

示例代码来自:https://github.com/prodigyeducation/python-graphql-client

代码语言:javascript
复制
client = GraphqlClient(endpoint="https://countries.trevorblades.com")
query = """
    query countryQuery($countryCode: String) {
        country(code:$countryCode) {
            code
            name
        }
    }
"""
variables = {"countryCode": "CA"}
data = client.execute(query=query, variables=variables)

这就像预期的那样工作正常。

您的代码(使用当前终结点URL更新)

代码语言:javascript
复制
from python_graphql_client import GraphqlClient

client = GraphqlClient('https://api.genetics.opentargets.org/graphql')
result = client.execute('''
query {
  manhattan(studyId: "GCST004599", pageIndex: 0, pageSize: 10000) {
    associations {
      variant {
        rsId
        altAllele
        refAllele
        nearestGene {
          id
        }
        nearestCodingGene {
          id
        }
      }
      pval
      bestGenes {
        gene {
          id
        }
        score
      }
      credibleSetSize
      ldSetSize
    }
  }
}
''')
print(result)

如果你正在调整你的查询字符串,你就做错了!请改用变量。这就是GraphQL的设计用法。

正性骨盆入路

代码语言:javascript
复制
result = client.execute('''
query associationsQuery($id: String) {
  manhattan(studyId: $id, pageIndex: 0, pageSize: 10000) {
    associations {
      variant {
        rsId
        altAllele
        refAllele
        nearestGene {
          id
        }
        nearestCodingGene {
          id
        }
      }
      pval
      bestGenes {
        gene {
          id
        }
        score
      }
      credibleSetSize
      ldSetSize
    }
  }
}
''', variables={id: "GCST004599"})

现在,这种方法是干净的,人类可读的,并且不涉及任何Python字符串损坏。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53510102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档