diff options
author | Ken Payson <kpayson@google.com> | 2016-06-27 14:12:08 -0700 |
---|---|---|
committer | Ken Payson <kpayson@google.com> | 2016-06-29 17:49:19 -0700 |
commit | 6a654dd400cc204a1ceb059785821c8ea15acde9 (patch) | |
tree | 7cbdef066db3e8c442b00c61b62d81c2b11b0ac9 /src/python/grpcio/grpc/_common.py | |
parent | b4028f6675a3c3d24fdbb3bed4e4a3939ccbb434 (diff) |
Changed default string type to be str
This impacts the following APIs:
Metadata: Key is always a str, Value is bytes for binary metadata,
str otherwise
Call Details: str type
gRPC method: str type
hostname/target: str type
Diffstat (limited to 'src/python/grpcio/grpc/_common.py')
-rw-r--r-- | src/python/grpcio/grpc/_common.py | 43 |
1 files changed, 31 insertions, 12 deletions
diff --git a/src/python/grpcio/grpc/_common.py b/src/python/grpcio/grpc/_common.py index f351bea9e3..4d7d521419 100644 --- a/src/python/grpcio/grpc/_common.py +++ b/src/python/grpcio/grpc/_common.py @@ -76,9 +76,37 @@ STATUS_CODE_TO_CYGRPC_STATUS_CODE = { } -def metadata(application_metadata): +def encode(s): + if isinstance(s, bytes): + return s + else: + return s.encode('ascii') + + +def decode(b): + if isinstance(b, str): + return b + else: + try: + return b.decode('utf8') + except UnicodeDecodeError: + logging.exception('Invalid encoding on {}'.format(b)) + return b.decode('latin1') + + +def cygrpc_metadata(application_metadata): return _EMPTY_METADATA if application_metadata is None else cygrpc.Metadata( - cygrpc.Metadatum(key, value) for key, value in application_metadata) + cygrpc.Metadatum(encode(key), encode(value)) + for key, value in application_metadata) + + +def application_metadata(cygrpc_metadata): + if cygrpc_metadata is None: + return () + else: + return tuple( + (decode(key), value if key[-4:] == b'-bin' else decode(value)) + for key, value in cygrpc_metadata) def _transform(message, transformer, exception_message): @@ -101,17 +129,8 @@ def deserialize(serialized_message, deserializer): 'Exception deserializing message!') -def _encode(s): - if isinstance(s, bytes): - return s - else: - return s.encode('ascii') - - def fully_qualified_method(group, method): - group = _encode(group) - method = _encode(method) - return b'/' + group + b'/' + method + return '/{}/{}'.format(group, method) class CleanupThread(threading.Thread): |