python - 带有变量的Python多行graphql突变-KeyError
问题描述
所以我正在尝试编写一个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 查询实际上将返回数据,插入 throw 的突变将不起作用并失败,并出现以下错误 Traceback:
Traceback (most recent call last):
File "./input.py", line 25, in <module>
result2 = client.execute('''
KeyError: '\n createThrow(playerId'
从我想说的几个小时开始,我就在尝试这个,但不知道该怎么做。当我将变量硬编码到查询中而不是格式化多行字符串时,它会正常工作。所以基本的突变会起作用。问题必须是用变量格式化字符串。
我还尝试了 f-strings、命名格式和我知道的任何其他技巧。
因此,如果有人能指出我的大致方向,我将不胜感激。
解决方案
https://stackoverflow.com/a/10986239/6124657
Variables in graphql SHOULD BE DEFINED SEPARATELY
formatting the string with variables
... is ABUSING GRAPHQL !!!
In this case it should be 2nd parameter of client.execute
推荐阅读
- java - 如果在字符串中,则无法在 SQL 中设置命名(或序数)参数
- node.js - 将参数传递给 node.js domain.on('error'...)
- c# - 如何从 Unity Android 应用程序打开 Android 系统设置
- javascript - 使用 ed25519 密钥从 nodejs SSH 到服务器
- javascript - 将用布尔值填充的对象转换为布尔值为真的字符串数组
- swift - 协议中的 Swift 元组声明
- jms - 如何使用 Open Liberty 和 IBM MQ 实现 FIFO 范式?
- node.js - Node js,等待,直到从 MongoDB 获取所有数据
- java - 如何将行转换为数据集
在火花 Java 中
- c# - 如果我在发布后不断重建我的视图模型,这是否表明存在重大设计缺陷?