【问题标题】:Making a graphQL mutation from my python code, getting error从我的 python 代码中进行 graphQL 突变,得到错误
【发布时间】:2018-07-19 12:21:55
【问题描述】:

我正在尝试从 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 中起作用的突变示例如下:

"mutation {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}]}]}

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

【问题讨论】:

  • 在字符串、电子邮件和密码中尝试使用双引号 (") 而不是单引号。
  • 同样的问题。查询有效,但突变无效,我尝试命名突变,但语法错误仍然相同。想知道请求库是否对作为 val 传递的字符串做了一些有趣的事情。

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


【解决方案1】:

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)

【讨论】:

【解决方案2】:

我通过浏览器跟踪突变请求,并准确复制了正在发送的 json,删除了换行符。在我添加的代码中 { "query": json } 并且它起作用了

我使用发送 2 个参数并接收令牌的示例:

mutation = """mutation {  
    login(    username: "myusername",    password: "mypassword",  ) 
        {   
            token 
        }
    }"""
    
res = requests.post(url, json={"query": mutation} )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2016-10-18
    • 2021-11-26
    相关资源
    最近更新 更多