定义GraphQL模式的简单方法
gqltype的Python项目详细描述
说明
目前正在试验中。在
gqltype
是来自python类型注释的GraphQL模式生成器。在
特点
- 通过python类型注释简单定义GraphQL模式
- 基于
graphql-core>=3.0
库生成架构 - asgi友好型
安装
使用pip
$ pip install gqltype
使用poetry
快速介绍
假设我们要对https://graphql.org/learn/schema/教程开头提到的模式进行建模。在
fromdataclassesimportdataclassfromenumimportEnumfromtypingimportListimportgqltypeclassEpisode(Enum):"""Codename for the episodes"""NEWHOPE="new hope"EMPIRE="empire"JEDI="jedi"@dataclassclassCharacter:"""An individual person within the Star Wars universe"""name:strappears_in:List[Episode]classLengthUnit(Enum):"""Measure of length"""METER="meter"INCH="inch"@dataclassclassStarship:"""A single transport craft that has hyperdrive capability"""id:strname:strlength:floatdefresolve_length(self,unit:LengthUnit=LengthUnit.METER)->float:ifunit==LengthUnit.INCH:returnself.length/0.0254returnself.lengthdefget_character()->Character:returnCharacter(name="R2D2",appears_in=[Episode.JEDI,Episode.NEWHOPE])asyncdefget_starship()->Starship:returnStarship(id="F1000",name="Millennium Falcon",length=34.75)defadd_character(name:str,appears_in:List[Episode])->Character:returnCharacter(name=name,appears_in=appears_in)schema=gqltype.Schema(queries=[get_character,get_starship],mutations=[add_character])fromgraphql.utilitiesimportprint_schemaprint(print_schema(schema.build()))
它将产生以下输出
type Query { getCharacter: Character! getStarship: Starship! } """An individual person within the Star Wars universe""" type Character { appearsIn: [Episode!]! name: String! } """Codename for the episodes""" enum Episode { NEWHOPE EMPIRE JEDI } """A single transport craft that has hyperdrive capability""" type Starship { length(unit: LengthUnit! = METER): Float! id: ID! name: String! } """Measure of length""" enum LengthUnit { METER INCH } type Mutation { addCharacter(name: String!, appearsIn: [Episode!]!): Character! }
为了用这个模式运行服务器,我们可以使用Starlette
if__name__=="__main__":importuvicornfromgqltype.contrib.starletteimportGraphQLAppfromstarlette.applicationsimportStarlettefromstarlette.routingimportRouteapp=Starlette(routes=[Route("/graphql",GraphQLApp(schema=schema))])uvicorn.run(app)
执行
{ getCharacter { name appearsIn } getStarship { id name length(unit: INCH) } }
给予
{"data":{"getCharacter":{"name":"R2D2","appearsIn":["JEDI","NEWHOPE"]},"getStarship":{"id":"F1000","name":"Millennium Falcon","length":1368.1102362204724}}}
托多
- 在
健全性检查
- 如果类和解析方法指定了不同的类型,则发出警告
- 在
某些类型的通用解析器?在
在 - 在
gqltype.F?--字段定义
在 - 在
核心部分和高级部分
在 - 在
业务层面
- 输入值验证
- 输出值的序列化
- 项目
标签: