【发布时间】:2019-05-11 22:03:54
【问题描述】:
有很多 GUI 客户端,如 GraphQL Playground、GraphiQl 等,它们能够从 URL 获取 GraphQL 架构。如何使用 Python 获取架构?
【问题讨论】:
标签: python python-3.x python-requests graphql
有很多 GUI 客户端,如 GraphQL Playground、GraphiQl 等,它们能够从 URL 获取 GraphQL 架构。如何使用 Python 获取架构?
【问题讨论】:
标签: python python-3.x python-requests graphql
来自规范:
GraphQL 服务器支持对其架构进行自省。该模式使用 GraphQL 本身进行查询,为工具构建创建了一个强大的平台......模式自省系统可从元字段 __schema 和 __type 访问,这些元字段可从查询操作的根类型访问。
GraphQL Playground 和 GraphiQL 等工具利用自省来获取有关模式的信息。您不需要任何额外的工具或库来进行自省查询——因为它只是一个 GraphQL 查询,您将像向端点发出任何其他请求一样发出请求(例如使用 requests)。
这是来自graphql-core 的完整自省查询:
introspection_query = """
query IntrospectionQuery {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
description
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
description
fields(includeDeprecated: true) {
name
description
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
description
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
description
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
"""
【讨论】:
graphql-core 具有实用程序来获取查询并转换查询结果。这是一个在 sdl 中打印结果模式的示例 sn-p:
from graphqlclient import GraphQLClient
from pprint import PrettyPrinter
from graphql import get_introspection_query, build_client_schema, print_schema
def main():
pp = PrettyPrinter(indent=4)
client = GraphQLClient('http://swapi.graph.cool/')
query_intros = get_introspection_query(descriptions=True)
intros_result = client.execute(query_intros, variables=None, operationName=None)
client_schema = build_client_schema(intros_result.get('data', None))
sdl = print_schema(client_schema)
print(sdl)
pp.pprint(sdl)
我一直在寻找相同的内容,最后找到了上述内容。
【讨论】:
TypeError: execute() got an unexpected keyword argument 'operationName'