基于aiohttp和graphql-core-next构建的异步GraphQL客户端
项目描述
异步GraphQL客户端
一个基于aiohttp和graphql-core-next构建的异步GraphQL客户端。客户端默认会内省模式并验证所有查询,然后再将其发送到服务器。
文档
有关最新的项目文档,您可以访问 https://aiographql-client.readthedocs.io/。
安装
pip install aiographql-client
示例用法
以下是此客户端实现的一些示例用法。有关更多示例和高级场景,请参阅文档中的 使用示例 部分。
简单查询
async def get_logged_in_username(token: str) -> GraphQLResponse:
client = GraphQLClient(
endpoint="https://api.github.com/graphql",
headers={"Authorization": f"Bearer {token}"},
)
request = GraphQLRequest(
query="""
query {
viewer {
login
}
}
"""
)
return await client.query(request=request)
>>> import asyncio
>>> response = asyncio.run(get_logged_in_username("<TOKEN FROM GITHUB GRAPHQL API>"))
>>> response.data
{'viewer': {'login': 'username'}}
查询订阅
async def print_city_updates(client: GraphQLClient, city: str) -> None:
request = GraphQLRequest(
query="""
subscription ($city:String!) {
city(where: {name: {_eq: $city}}) {
description
id
}
}
""",
variables={"city": city},
)
# subscribe to data and error events, and print them
await client.subscribe(
request=request, on_data=print, on_error=print, wait=True
)
有关自定义事件特定回调注册,请参阅 回调注册文档。
查询验证失败
如果您的查询无效,多亏了graphql-core-next,我们可以在跟踪信息中获得详细的异常。
aiographql.client.exceptions.GraphQLClientValidationException: Query validation failed
Cannot query field 'ids' on type 'chatbot'. Did you mean 'id'?
GraphQL request (4:13)
3: chatbot {
4: ids, bot_names
^
5: }
Cannot query field 'bot_names' on type 'chatbot'. Did you mean 'bot_name' or 'bot_language'?
GraphQL request (4:18)
3: chatbot {
4: ids, bot_names
^
5: }
查询变量和操作
客户端支持多操作请求和变量。例如,以下请求包含多个操作。实例指定了默认值。
request = GraphQLRequest(
query="""
query get_bot_created($id: Int) {
chatbot(where: {id: {_eq: $id}}) {
id, created
}
}
query get_bot_name($id: Int) {
chatbot(where: {id: {_eq: $id}}) {
id, bot_name
}
}
""",
variables={"id": 109},
operation="get_bot_name"
)
如果需要,可以在发出请求时覆盖默认值。
await client.query(request=request, variables={"id": 20}, operation="get_bot_created")
项目详情
关闭
aiographql_client-1.1.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 9ea7a03dd0f1bf4e034234b64064ca39608dea188dafe592752fb34092421a41 |
|
MD5 | 7060e7176d9382880818b12c96ba9cfa |
|
BLAKE2b-256 | 0deef070997ed988a6e00e7415bc2cb947321236a3af253ebab10db9656d421f |
关闭
aiographql_client-1.1.0-py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 67b2d92086558d07c43db8071a9b9a328df7786b72d172ce7dddff4ddefa52aa |
|
MD5 | f433bd5e245ee0cc1710b28527479500 |
|
BLAKE2b-256 | 5b1c039955d3f78aa328b62cc80e69b6339675ecee3b9d25035b477f756e8a4a |