首页 > 解决方案 > 如何在 python-gql 中使用变量?

问题描述

此函数将返回所有用户而不是提供用户名,我怎样才能使它正确?还有更好的 Python GraphQL 客户端吗?gql 非常简单,以至于没有多少文件可以检查。

    def fetch_user(username):
        query = gql("""
                    query getUser($username: String) {
                    user(
                        where: { name: { _eq: $username } }
                    ) {
                        id
                        name
                    }
                    }
                """)
        result = client.execute(query)

标签: graphqlgraphql-python

解决方案


您可以在参数的帮助下使用graphql-python/gqlvariable_values中的变量。这是我使用该变量的代码片段。

query = gql("""
mutation ($paramId: ID!, $paramTitle: String!){
    XputPost(id: $paramId, title: $paramTitle){
        id
        title
    }
}
""")

params = {
    "paramId": "1",
    "paramTitle": "New Post"
}
result = client.execute(query, variable_values=params)

我希望这个答案对你有所帮助。


推荐阅读