Python-GraphQL生成的代码客户端
py-gql-client的Python项目详细描述
pygqlclient是一个python库,它创建用于根据graphql模式查询graphql的强类型类。 它类似于为诸如gRPC和Thrift这样的API模式类型生成代码的库。在
这对于快速、安全地构建基于GraphQL的SDK非常有帮助,因为它可以帮助您保证以下几点:
- GraphQL查询是有效的-在编译时和运行时验证
- Python查询的使用是有效的-用户可以使用mypy验证它(库与mypy兼容-http://mypy-lang.org/)
- graphql模式中随着时间的变化不会破坏现有的SDK—您可以使用编译器的verify标志并将其集成到您的CI/CD中
Graphql是Facebook开发的一种查询语言(https://graphql.org/)
安装
- 安装时:
pip install py-gql-client
使用
安装后,您应该使用running编译代码
^{pr2}$schema_library
是graphql模式(或多个模式)所在的文件夹graphql_library
是您要编译的查询的位置(Query
、Mutation
和{})的位置
示例:
在graphql_library
中创建文件query.graphql
:
query DogQuery($id: String!) { dog(id: $id) { id name breed age } }
编译后,它将在同一文件夹中创建文件query.py
:
#!/usr/bin/env python3# @generated AUTOGENERATED file. Do not Change!fromdataclassesimportdataclass,fieldfromdatetimeimportdatetimefromgql_client.runtime.datetime_utilsimportDATETIME_FIELD_METADATAfromgql_client.runtime.variablesimportencode_variablesfromgqlimportgql,Clientfromgql.transport.exceptionsimportTransportQueryErrorfromfunctoolsimportpartialfromnumbersimportNumberfromtypingimportAny,AsyncGenerator,Callable,Dict,List,Generator,Optionalfromtimeimportperf_counterfromdataclasses_jsonimportDataClassJsonMixinfromgql_client.runtime.enum_utilsimportenum_field_metadatafrom.enum.dog_breedimportDogBreed# fmt: offQUERY:List[str]=["""query DogQuery($id: String!) { dog(id: $id) { id name breed age }}"""]classDogQuery:@dataclass(frozen=True)classDogQueryData(DataClassJsonMixin):@dataclass(frozen=True)classDog(DataClassJsonMixin):id:strname:Optional[str]age:Optional[int]breed:Optional[DogBreed]=field(metadata=enum_field_metadata(DogBreed))dog:Optional[Dog]# fmt: off@classmethoddefexecute(cls,client:Client,id:str)->Optional[DogQueryData.Dog]:variables:Dict[str,Any]={"id":id}new_variables=encode_variables(variables)response_text=client.execute(gql("".join(set(QUERY))),variable_values=new_variables)res=cls.DogQueryData.from_dict(response_text)returnres.dog# fmt: off@classmethodasyncdefexecute_async(cls,client:Client,id:str)->Optional[DogQueryData.Dog]:variables:Dict[str,Any]={"id":id}new_variables=encode_variables(variables)response_text=awaitclient.execute_async(gql("".join(set(QUERY))),variable_values=new_variables)res=cls.DogQueryData.from_dict(response_text)returnres.dog
要使用新类,首先需要使用gql库(https://github.com/graphql-python/gql)初始化graphql客户机。库中有许多用于定义底层传输的选项,请查看文档以了解更多信息。在
完整的简单示例如下:
fromgqlimportClientfromgql.transport.aiohttpimportAIOHTTPTransportfromgql_client.runtime.graphql_clientimportGraphqlClientfromqueryimportDogQuerytransport=AIOHTTPTransport(url="http://.../graph/query")client=Client(transport=transport,fetch_schema_from_transport=True)result=DogQuery.execute(client,id="1000")...
您可以在examples
目录中找到更多示例
更多功能
- 创建片段查询文件并在其他查询文件之间共享它们
- 编译器可以选择只验证已编译的查询文件而不重新生成它们
- 编译器可以配置为在查询使用不推荐的字段时引发错误
许可证
pygql客户端是BSD License
授权的,如LICENSE
文件中所示。在
- 项目
标签: