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.0.tar.gz (7.0 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.0-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: asyncgrpcclient-1.0.0.tar.gz
  • Upload date:
  • Size: 7.0 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.0.tar.gz
Algorithm Hash digest
SHA256 eb5f5bd454af718972c46598e214b5e154e71e720f85ae53f0be51508767936b
MD5 cc2981fcfb2ab2316620b787f1977460
BLAKE2b-256 d2ba3e38863051ca29a4e0ef000a932270fc3175192371e3b64009332e5bf526

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for asyncgrpcclient-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e46dc86c034b65efea6204ca0a5d3279686a20960f1d7b0a3cd656bcb5e93a4e
MD5 6952b88dbf7e5dc8596c8abb1b0a277a
BLAKE2b-256 bad33ef354b53c79123b9a1e852e1491ff6a9cdc832d3c6910cabe5902a8dc2b

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