Skip to main content

Interceptors for grpc

Project description

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 .

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

agi_med_grpc_interceptors-2.0.2.tar.gz (7.4 kB view details)

Uploaded Source

Built Distribution

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

agi_med_grpc_interceptors-2.0.2-py3-none-any.whl (9.2 kB view details)

Uploaded Python 3

File details

Details for the file agi_med_grpc_interceptors-2.0.2.tar.gz.

File metadata

File hashes

Hashes for agi_med_grpc_interceptors-2.0.2.tar.gz
Algorithm Hash digest
SHA256 a4a4e43d4f03917d7933b31f7be42942c26be6d42f01c05e06e8acd2df16464b
MD5 701adbe6798a4115bbc79015a1dc13f1
BLAKE2b-256 0065752706120199cc93ae51f73fd5a35de880eb535ad1dd72915e273dbc5564

See more details on using hashes here.

File details

Details for the file agi_med_grpc_interceptors-2.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for agi_med_grpc_interceptors-2.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 40f169b3d60473c02ec02293defc110f90a132f95bc9ba6ca722b33290dd8641
MD5 66a300c8fc7bcc6c62617779ba0af617
BLAKE2b-256 44d938346d35592bd830e46e702dde7d4b9edeb6a1dce18ea67bca1150dc184f

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