Catalog PyPI
Back to packageRELEASE DETAILS

3.2.0

PyPI

agi-med-grpc-interceptors

Interceptors for grpc

Published26 Feb 2025
Direct dependencies4
Transitive dependenciesNot calculated

README

Version 3.2.0 documentation

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 .

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Declared dependencies 4

Native requirements
4 direct targetsNot calculated transitive count
Package / targetRequirementRelationship
grpcio
Environment
{
  "extras": "",
  "marker": null,
  "requires_python": ">=3.11",
  "evaluation": "NOT_EVALUATED"
}
grpcio~=1.68.1runtime
grpcio-tools
Environment
{
  "extras": "",
  "marker": null,
  "requires_python": ">=3.11",
  "evaluation": "NOT_EVALUATED"
}
grpcio-tools~=1.68.1runtime
loguru
Environment
{
  "extras": "",
  "marker": null,
  "requires_python": ">=3.11",
  "evaluation": "NOT_EVALUATED"
}
loguru~=0.7.2runtime
pydantic
Environment
{
  "extras": "",
  "marker": null,
  "requires_python": ">=3.11",
  "evaluation": "NOT_EVALUATED"
}
pydantic~=2.9.2runtime

Distribution files

2 collected
agi_med_grpc_interceptors-3.2.0-py3-none-any.whl

bdist_wheel · 8.78 KB · Python py3

Source file
agi_med_grpc_interceptors-3.2.0.tar.gz

sdist · 6.94 KB · Python source

Source file

Metadata history

Meaningful changes
Current collected state Current

Observed since 21 Oct, 09:08 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package_version:6a2b70e90af225498a9331f36e34fe0b34cd526c2ab2f47ee7c7b0ab473c8677

Other collected versions

View all collected versions →