在Python graphql-core中使用Relay遇重复Query类型错误的解决方法
问题:GraphQL-core处理Relay自引用Query类型时抛出TypeError错误
执行以下Python代码时会抛出TypeError: Schema must contain uniquely named types but contains multiple types named 'Query'.错误:
import json from graphql.utilities import build_schema from graphql.type import GraphQLObjectType, GraphQLSchema def read_file(file_path, is_json: bool = False): file_contents = None try: with open(file_path, "r") as file: file_contents = file.read() except FileNotFoundError: print(f"File '{file_path}' not found.") except IOError: print(f"Error reading file '{file_path}'.") if not file_contents: raise Exception("GraphQL schema is empty") return json.loads(file_contents) if is_json else file_contents schema = build_schema(read_file("schemas/github.graphql")) GraphQLSchema(GraphQLObjectType('Query', lambda:schema.query_type.fields))
GitHub的GraphQL公共Schema包含如下Relay Query类型定义:
type Query { ... """ Workaround for re-exposing the root query object. (Refer to https://github.com/facebook/relay/issues/112 for more information.) """ relay: Query! ... }
在Python graphql-core库中使用该Schema重建时触发上述错误,请问这是graphql-core的bug吗?应如何正确处理此类Relay场景?
回答
这不是graphql-core的bug,问题出在你手动重建Schema的方式有误。build_schema函数已经自动处理了Schema中的自引用类型(比如这里的relay: Query!),并生成了完整可用的Schema对象,完全不需要再手动创建GraphQLObjectType和GraphQLSchema。
你最后一行代码手动创建了一个新的GraphQLObjectType并命名为'Query',但build_schema返回的schema对象里已经存在一个同名的Query类型。当你用这个新类型构建GraphQLSchema时,就会因为存在重复命名的类型触发报错。
正确做法:直接使用build_schema生成的Schema对象
把代码最后一行替换成直接使用已生成的schema即可:
# 直接用build_schema生成的schema,它已经处理好自引用关系 print(schema.query_type.fields) # 可以验证Query类型的字段是否正常加载
如果需要扩展Schema
要是你需要给现有Schema添加字段或做其他修改,直接在build_schema生成的Schema基础上操作就行,不要重新创建同名类型。比如添加一个新字段:
from graphql.type import GraphQLString # 给已有的Query类型添加新字段 schema.query_type.fields['newCustomField'] = GraphQLString()
内容的提问来源于stack exchange,提问作者jdcaballerov
相关产品推荐
相关产品推荐

