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

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for agi_med_grpc_interceptors-2.0.0.tar.gz
Algorithm Hash digest
SHA256 36817f7a78f296e29c20fb47d6efaf894a241083fca25d8d2c4a8ec0de7cce97
MD5 200455c774739b3ceeda93150a5737ea
BLAKE2b-256 b1a67cf3b82cd4f119eb29c457c7be4ab56d99bfa920a63b61b89d077ec81a8e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for agi_med_grpc_interceptors-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8ba9724a2c10bc6dc8e35c5ceaadc36da4fbff0a0919474b03c516bc46d6ca18
MD5 88e783cf0d68914097544ac18bdb4253
BLAKE2b-256 d881035f2750366d9c3582a2b1f641a053ddf4fff6e6b35f38f03cf8808c5a86

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