跳转到主要内容

基于aiohttp和graphql-core-next构建的异步GraphQL客户端

项目描述

异步GraphQL客户端

PyPI version Python Versions License: MIT Documentation Status Code style: black Sonarcloud Status

一个基于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 (13.8 kB 查看哈希值)

上传时间

构建分发

aiographql_client-1.1.0-py3-none-any.whl (14.9 kB 查看哈希值)

上传时间 Python 3

由以下组织支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面