首页 > 解决方案 > 带有变量的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、命名格式和我知道的任何其他技巧。

因此,如果有人能指出我的大致方向,我将不胜感激。

标签: pythongraphql

解决方案


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

Read docs
Python example


推荐阅读