python - 从我的 python 代码中进行 graphQL 突变,出现错误

标签 python python-requests graphql parse-error express-graphql

我正在尝试从 python 对我的 Shopify 商店进行修改。 我是 graphQL 的新手,我已经能够使用 graphiQL 进行突变,但我不确定如何直接从我的代码中进行突变。

这是我的 make 查询文件,它已成功用于简单查询

`import requests 
 def make_query(self, query, url, headers):
    """
    Return query response
    """
    request = requests.post(url, json={'query': query}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))`

现在在 graphiQL 中起作用的突变示例是这样的:

“突变{customerCreate(input: {email: 'wamblamkazam@send22u.info', password: 'password'}) {userErrors { field message}customer{id}}}”

但是当我将它传递到我的 make_query 函数时它给出了这个错误

{'errors': [{'message': 'Parse error on "\'" (error) at [1, 41]', 'locations': [{'line': 1, 'column': 41}]}]}

我该如何解决这个问题? 此外,我正在使用变量进行的其中一个突变,但我无法直接从我的代码中找到如何执行此操作的示例

最佳答案

GraphQl 提供了一种以 JSON 格式发送数据的方法。您可以在查询中使用变量,并将 JSON 对象作为变量值发送:

def make_query(self, query, variables, url, headers):
    """
    Make query response
    """
    request = request.post(url, json={'query': query, 'variables': variables}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))

查询看起来像这样:

query = """
    mutation CreateCustomer($input:CustomerInput){
        customerCreate(customerData: $input){
            customer{
                name
            }
        }
    }
"""
variables = {'input': customer}

您还可以使用类似 python-graphql-client 的库 提出相同的要求:

client = GraphQLClient('http://127.0.0.1:5000/graphql')

query = """
mutation CreateCustomer($input:CustomerInput){
    customerCreate(customerData: $input){
        customer{
            name
        }
    }
}
"""

variables = {'input': customer}

client.execute(query, variables)

关于python - 从我的 python 代码中进行 graphQL 突变,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693825/

相关文章:

python - 如何从 api 响应中提取 application/zip?

python - 使用 Python 请求选择表单

python - 在 Django 2.2 中为 GRAPHENE 设置 'SCHEMA' 导入模块时出现问题

python - 训练 Keras 模型时使用稀疏数组表示标签

python - 无法使用请求从 zillow 中抓取自定义属性链接

reactjs - 有没有办法在没有 GraphQL 的情况下使用 Relay?

graphql - Graphql-如何执行where子句

python - 拦截 SQLAlchemy 中模型的所有查询

python - 如何用 Python 将变量写成二进制数据?

python - 使用多数据库的 Django 事务