我正在尝试从 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/