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 (Пример ниже)
Примеры
- Подключение 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()],
)
- Реализация ошибки для сервиса
#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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file agi_med_grpc_interceptors-3.2.0.tar.gz.
File metadata
- Download URL: agi_med_grpc_interceptors-3.2.0.tar.gz
- Upload date:
- Size: 7.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dc5d17b8a68272f07f410099e2abef4b82e703fd1238f3663aa6a137e7146023
|
|
| MD5 |
dea0002a7d062891b730ce0e3542e15a
|
|
| BLAKE2b-256 |
5458ef110507b730408e5a1522d7c9b7b078f42c6709521bddd9f12d201dbab2
|
File details
Details for the file agi_med_grpc_interceptors-3.2.0-py3-none-any.whl.
File metadata
- Download URL: agi_med_grpc_interceptors-3.2.0-py3-none-any.whl
- Upload date:
- Size: 9.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
30d9eafc3dcf3ac582dea3582a1380581732ae410753d5b64c601ef118f36967
|
|
| MD5 |
4698bddaca8379251d1bf77c3c90b8a6
|
|
| BLAKE2b-256 |
95e0b37b6f2bd15bac853a69066f27d270caefff8431db13909df61054b15205
|