Skip to main content

agi-med-grpc-interceptors

Стандартные middlewares для grpc

Ответственный разработчик

@zhelvakov

Общая информация

  • LoggingInterceptor - работает на loguru. Принимает metadata, забирает все хедеры и пытается использовать как контекст, по-умолчанию дополнительно прописывает uuid в контекст. Обработка ошибок может быть переопределена с помощью метода exception_handler
  • ExcHandlerInterceptor - добавляет подсчет ошибок с помощью prometheus: error_counter[path, status_code, error]. Обрабатывает ошибки, которые наследуются от BaseGrpcError (Пример ниже)

Примеры

  1. Подключение interceptors
import grpc
from concurrent import futures

from agi_med_grpc_interceptors import LoggingInterceptor, ExcHandlerInterceptor


server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=10),
        interceptors=[LoggingInterceptor(), ExcHandlerInterceptor()],
    )
  1. Реализация ошибки для сервиса
#server
from agi_med_grpc_interceptors import BaseGrpcError, DefaultValue
from grpc import StatusCode

from .some_protos.Some_pb2_grpc import SomeServicer
from .Some_pb import GetSalaryResponse, GetSalaryRequest


class EmployerNotFound(BaseGrpcError[float]):
    def __init__(self, message: str) -> None:
        default_value = DefaultValue[float](value=0)
        super().__init__(StatusCode.ALREADY_EXISTS, message, default_value)

class Some(SomeServicer):
    def GetSalary(self, request: GetSalaryRequest) -> GetSalaryResponse:
        if request.Username == "bob":
            raise EmployerNotFound("Bob, go to home!")
        return GetSalaryResponse(salary=10_000)

#client
from agi_med_grpc_interceptors import BaseGrpcError, ErrorDetails
from grpc import RpcError

from .Some_pb import GetSalaryResponse, GetSalaryRequest
from .Some_pb2_grpc import SomeStub


stub = SomeStub("0.0.0.0:5000")

try:
    request = GetSalaryRequest(Username="bob")
    response: GetSalaryResponse = stub.DoSomething(request)
except RpcError as ex:
    error: ErrorDetails[float] | None = BaseGrpcError[float].extract_error(ex)
    default_value: float | None = BaseGrpcError[float].extract_default_value_from_error(ex)
    print(f"{error=}")
    print(f"{default_value=}")

Линтеры

pip install black flake8-pyproject mypy
black .
flake8
mypy .

Metadata

Release files for agi-med-grpc-interceptors 3.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agi-med-grpc-interceptors 3.2.0
File Size Uploaded Provenance Actions
agi_med_grpc_interceptors-3.2.0.tar.gz 7.1 kB Without provenance Details for agi_med_grpc_interceptors-3.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agi-med-grpc-interceptors 3.2.0
File Interpreter ABI Platform Actions
agi_med_grpc_interceptors-3.2.0-py3-none-any.whl Python 3 none any Details for agi_med_grpc_interceptors-3.2.0-py3-none-any.whl

Total release size: 16.1 kB

Release files / agi_med_grpc_interceptors-3.2.0.tar.gz

Download URL agi_med_grpc_interceptors-3.2.0.tar.gz
Size 7.1 kB
Tags Source
SHA-256 checksum
How to use checksums
dc5d17b8a68272f07f410099e2abef4b82e703fd1238f3663aa6a137e7146023
BLAKE2b-256 checksum
How to use checksums
5458ef110507b730408e5a1522d7c9b7b078f42c6709521bddd9f12d201dbab2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.13.2

Release files / agi_med_grpc_interceptors-3.2.0-py3-none-any.whl

Download URL agi_med_grpc_interceptors-3.2.0-py3-none-any.whl
Size 9.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
30d9eafc3dcf3ac582dea3582a1380581732ae410753d5b64c601ef118f36967
BLAKE2b-256 checksum
How to use checksums
95e0b37b6f2bd15bac853a69066f27d270caefff8431db13909df61054b15205
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.13.2

Security for agi-med-grpc-interceptors 3.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page