所以我试图编写一个graphql python脚本,该脚本将向我的后端发送变异。因此,我创建了一个“客户端”模块(基于https://github.com/prisma-labs/python-graphql-client)来导出一个类GraphQLClient,如下所示:
import urllib.request
import json
class GraphQLClient:
def __init__(self, endpoint):
self.endpoint = endpoint
def execute(self, query, variables=None):
return self._send(query, variables)
def _send(self, query, variables):
data = {'query': query,
'variables': variables}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
req = urllib.request.Request(
self.endpoint, json.dumps(data).encode('utf-8'), headers)
try:
response = urllib.request.urlopen(req)
return response.read().decode('utf-8')
except urllib.error.HTTPError as e:
print((e.read()))
print('')
raise e
到目前为止,一切都很好。我的主要代码现在看起来像这样,只是为了测试一切是否正常:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from client import GraphQLClient
if __name__ == "__main__":
playerId = 3
_round = 3
number = 5
modifier = 3
client = GraphQLClient('http://localhost:4000/graphql')
result = client.execute('''
{
allPlayers {
id
name
nickname
}
}
''')
result2 = client.execute('''
mutation{
createThrow(playerId: {}, round: {}, number:{}, modifier:{}) {
id
round
number
modifier
}
}
'''.format(playerId, _round, number, modifier))
print(result)
print(result2)
而allPlayers查询实际上将返回数据,插入投掷的突变将不起作用,并因以下错误Traceback而失败:
Traceback (most recent call last):
File "./input.py", line 25, in <module>
result2 = client.execute('''
KeyError: '\n createThrow(playerId'
我已经说了几个小时,但我一直在尝试,但无法弄清楚该怎么做。当我将变量硬编码到查询中而不是格式化多行字符串时,它将很好地工作。因此基本突变将起作用。问题必须是使用变量格式化字符串。
我也尝试过f字符串,命名格式和我知道的其他技巧。
因此,如果有人能指出我的一般方向,我将不胜感激。
https://stackoverflow.com/a/10986239/6124657
formatting the string with variables
...正在滥用GRAPHQL !!!
在这种情况下,它应该是execute
的第二个参数
读取docs