1# Copyright 2017 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Interceptor that adds headers to outgoing requests.""" 15 16import grpc 17 18 19class _ConcreteValue(grpc.Future): 20 def __init__(self, result): 21 self._result = result 22 23 def cancel(self): 24 return False 25 26 def cancelled(self): 27 return False 28 29 def running(self): 30 return False 31 32 def done(self): 33 return True 34 35 def result(self, timeout=None): 36 return self._result 37 38 def exception(self, timeout=None): 39 return None 40 41 def traceback(self, timeout=None): 42 return None 43 44 def add_done_callback(self, fn): 45 fn(self._result) 46 47 48class DefaultValueClientInterceptor( 49 grpc.UnaryUnaryClientInterceptor, grpc.StreamUnaryClientInterceptor 50): 51 def __init__(self, value): 52 self._default = _ConcreteValue(value) 53 54 def _intercept_call( 55 self, continuation, client_call_details, request_or_iterator 56 ): 57 response = continuation(client_call_details, request_or_iterator) 58 return self._default if response.exception() else response 59 60 def intercept_unary_unary(self, continuation, client_call_details, request): 61 return self._intercept_call(continuation, client_call_details, request) 62 63 def intercept_stream_unary( 64 self, continuation, client_call_details, request_iterator 65 ): 66 return self._intercept_call( 67 continuation, client_call_details, request_iterator 68 ) 69