| 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 |
|
| 16 |
import grpc |
| 17 |
|
| 18 |
|
| 19 |
class _ConcreteValue(grpc.Future): |
| 20 |
|
| 21 |
def __init__(self, result): |
| 22 |
self._result = result |
| 23 |
|
| 24 |
def cancel(self): |
| 25 |
return False |
| 26 |
|
| 27 |
def cancelled(self): |
| 28 |
return False |
| 29 |
|
| 30 |
def running(self): |
| 31 |
return False |
| 32 |
|
| 33 |
def done(self): |
| 34 |
return True |
| 35 |
|
| 36 |
def result(self, timeout=None): |
| 37 |
return self._result |
| 38 |
|
| 39 |
def exception(self, timeout=None): |
| 40 |
return None |
| 41 |
|
| 42 |
def traceback(self, timeout=None): |
| 43 |
return None |
| 44 |
|
| 45 |
def add_done_callback(self, fn): |
| 46 |
fn(self._result) |
| 47 |
|
| 48 |
|
| 49 |
class DefaultValueClientInterceptor(grpc.UnaryUnaryClientInterceptor, |
| 50 |
grpc.StreamUnaryClientInterceptor): |
| 51 |
|
| 52 |
def __init__(self, value): |
| 53 |
self._default = _ConcreteValue(value) |
| 54 |
|
| 55 |
def _intercept_call(self, continuation, client_call_details, |
| 56 |
request_or_iterator): |
| 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(self, continuation, client_call_details, |
| 64 |
request_iterator): |
| 65 |
return self._intercept_call(continuation, client_call_details, |
| 66 |
request_iterator) |