Skip to content

Commit 63c1e93

Browse files
authored
refactor: simplify metadata reading in grpc_handler.py (#685)
[`Metadata` is a `Collection`](https://grpc.github.io/grpc/python/_modules/grpc/aio/_metadata.html) so iterating over key-value tuples is possible, there are existing tests in `test_grpc_handler.py`. Re #676
1 parent 2e45c0d commit 63c1e93

1 file changed

Lines changed: 10 additions & 13 deletions

File tree

src/a2a/server/request_handlers/grpc_handler.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,12 @@
33
import logging
44

55
from abc import ABC, abstractmethod
6-
from collections.abc import AsyncIterable, Awaitable, Sequence
7-
from typing import TYPE_CHECKING
6+
from collections.abc import AsyncIterable, Awaitable
87

98

109
try:
1110
import grpc
1211
import grpc.aio
13-
14-
if TYPE_CHECKING:
15-
from grpc.aio._typing import MetadataType
16-
from grpc.aio import Metadata
1712
except ImportError as e:
1813
raise ImportError(
1914
'GrpcHandler requires grpcio and grpcio-tools to be installed. '
@@ -56,14 +51,16 @@ def build(self, context: grpc.aio.ServicerContext) -> ServerCallContext:
5651
def _get_metadata_value(
5752
context: grpc.aio.ServicerContext, key: str
5853
) -> list[str]:
59-
md: MetadataType | None = context.invocation_metadata()
60-
raw_values: list[str | bytes] = []
54+
md = context.invocation_metadata()
55+
if md is None:
56+
return []
57+
6158
lower_key = key.lower()
62-
if isinstance(md, Metadata):
63-
raw_values = md.get_all(lower_key)
64-
elif isinstance(md, Sequence):
65-
raw_values = [e for (k, e) in md if k.lower() == lower_key]
66-
return [e if isinstance(e, str) else e.decode('utf-8') for e in raw_values]
59+
return [
60+
e if isinstance(e, str) else e.decode('utf-8')
61+
for k, e in md
62+
if k.lower() == lower_key
63+
]
6764

6865

6966
class DefaultCallContextBuilder(CallContextBuilder):

0 commit comments

Comments
 (0)