graphene-python学习笔记(6)Interface
一、Interface
基础:
(1)任意定义实施了接口的ObjectType都将具有接口的字段。
(2)接口可以让你返回一个或一组不同的类的实例。根据运行时的参数决定返回哪一个实施了接口的ObjectType
示例:
定义接口:
import graphene
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
friends = graphene.List(lambda: Character)
2、实施接口
class Human(graphene.ObjectType):
class Meta:
interfaces = (Character, )
starships = graphene.List(Starship)
home_planet = graphene.String()
class Droid(graphene.ObjectType):
class Meta:
interfaces = (Character, )
primary_function = graphene.String()
相当于:
interface Character {
id: ID!
name: String!
friends: [Character]
}
type Human implements Character {
id: ID!
name: String!
friends: [Character]
starships: [Starship]
homePlanet: String
}
type Droid implements Character {
id: ID!
name: String!
friends: [Character]
primaryFunction: String
}
3、根据接口返回不同的类
class Query(graphene.ObjectType):
hero = graphene.Field(
Character,
required=True,
episode=graphene.Int(required=True)
)
def resolve_hero(_, info, episode):
# Luke is the hero of Episode V
if episode == 5:
return get_human(name='Luke Skywalker')
return get_droid(name='R2-D2')
schema = graphene.Schema(query=Query, types=[Human, Droid])
这样Query将根据查询时hero的参数决定是返回Human还是Droid。
使用inlinne fragement进行查询
query HeroForEpisode($episode: Int!) {
hero(episode: $episode) {
__typename
name
... on Droid {
primaryFunction
}
... on Human {
homePlanet
}
}
}
当参数是{ "episode": 4 }返回
{
"data": {
"hero": {
"__typename": "Droid",
"name": "R2-D2",
"primaryFunction": "Astromech"
}
}
}
当参数是{ "episode": 5 }时返回
{
"data": {
"hero": {
"__typename": "Human",
"name": "Luke Skywalker",
"homePlanet": "Tatooine"
}
}
}
当您在Graphene中构建schema时,解析器通常会返回表示支持GraphQL类型的数据的对象,而不是Graphene类型的实例(例如Django或SQLAlchemy模型)。这适用于ObjectType和Scalar字段,但是当您开始使用接口时,您可能会遇到此错误:
"Abstract type Character must resolve to an Object type at runtime for field Query.hero ..."
未解决上面的问题,我们需要定义一个resolve_type
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
@classmethod
def resolve_type(cls, instance, info):
if instance.type == 'DROID':
return Droid
return Human
将data object转变为graphene type
浙公网安备 33010602011771号