Skip to main content

Async gRPC client wrapper — callable URL/Metadata, error mapping, sync-style API over grpc.aio

Project description

asyncgrpcclient

Async gRPC client wrapper над grpc.aio — callable URL и Metadata, error mapping (StatusCode → exceptions), endpoint-aliasing, чистый API в стиле async REST-клиента.

Установка

pip install asyncgrpcclient

Возможности

  • ✅ Тонкая обёртка над grpc.aio.insecure_channel / secure_channel
  • ✅ Endpoints как именованные алиасы методов на gRPC stub
  • ✅ Per-call metadata override (поверх default)
  • ✅ Error mapping: grpc.aio.AioRpcErrorGrpcQueryError
  • Options с clone() / merge() для гибкой настройки timeout / status codes / extra kwargs
  • full_response режим (вернуть GrpcResponse или сам proto)

Быстрый старт

from asyncgrpcclient import AsyncGrpcClient

# stub сгенерирован из proto (grpc_tools.protoc → my_service_pb2_grpc.py)
from my_service_pb2_grpc import MyServiceStub
from my_service_pb2 import GetUserRequest

client = AsyncGrpcClient(
    stub=MyServiceStub,
    address="my-service:50051",
    endpoints={
        "get_user": "GetUser",
        "list_users": "ListUsers",
    },
    metadata={"x-tenant-id": "default"},
    timeout=5.0,
)

# через alias
user = await client("get_user", GetUserRequest(id=1))

# или напрямую через имя метода stub
user = await client("GetUser", GetUserRequest(id=1))

# с per-call metadata
user = await client(
    "get_user",
    GetUserRequest(id=1),
    metadata={"x-trace-id": "abc-123"},
)

# полный response объект
response = await client("get_user", GetUserRequest(id=1), full_response=True)
print(response.status_code, response.metadata)

await client.close()

Secure channel

import grpc

creds = grpc.ssl_channel_credentials(root_certificates=ca_pem)

client = AsyncGrpcClient(
    stub=MyServiceStub,
    address="my-service.example.com:443",
    secure=True,
    credentials=creds,
)

Error handling

from asyncgrpcclient import GrpcQueryError

try:
    user = await client("get_user", GetUserRequest(id=999))
except GrpcQueryError as exc:
    print(exc.code)   # grpc.StatusCode (NOT_FOUND, UNAVAILABLE, ...)
    print(exc.name)
    print(exc.message)

Options через ok_statuses

По умолчанию OK-статус: (grpc.StatusCode.OK,). Если нужно принять NOT_FOUND как валидный ответ:

import grpc

response = await client(
    "get_user",
    GetUserRequest(id=999),
    ok_statuses=[grpc.StatusCode.OK, grpc.StatusCode.NOT_FOUND],
    full_response=True,
)
if response.status_code == grpc.StatusCode.NOT_FOUND:
    user = None

API

Класс Описание
AsyncGrpcClient Основной клиент. __call__(endpoint, request, **opts)
BaseGrpcClient База с output() / parse_response_error()
GrpcURL host:port + endpoint alias mapping
GrpcMetadata Callable metadata, мерджит default + per-call
GrpcResponse Wrapper над proto response с status_code / metadata
ErrorResponse Для timeout / unavailable cases
GrpcQueryError Базовое исключение

Аналог

API параллелен sync REST-клиентам. Idiomatic для команд, у которых REST и gRPC живут вместе и хочется одинаковый стиль вызова.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

asyncgrpcclient-1.0.1.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

asyncgrpcclient-1.0.1-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file asyncgrpcclient-1.0.1.tar.gz.

File metadata

  • Download URL: asyncgrpcclient-1.0.1.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for asyncgrpcclient-1.0.1.tar.gz
Algorithm Hash digest
SHA256 3a5923da04fe04877f2a7a4567c3457089570192234cac36bdd6bf38157a481f
MD5 a6ce916490a93b12f599b354d0c35732
BLAKE2b-256 dbbed90411095b514817e7954318bfbac36677c22a84c0cae8a994b2d2cf48f9

See more details on using hashes here.

File details

Details for the file asyncgrpcclient-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for asyncgrpcclient-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 209267fa3cd47d6760791d78c4231f4b6d03e5d2f0fb7ed77a3aa8ce88bcefdd
MD5 e7157b1f07066a90e9fe03c9779a6f42
BLAKE2b-256 3c83f4b7be17c115c0ed55afcfdae5237b20f0d7198610b664f4af7b517ccce4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page