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 collections
17
18import generic_client_interceptor
19import grpc
20
21
22class _ClientCallDetails(
23    collections.namedtuple(
24        "_ClientCallDetails", ("method", "timeout", "metadata", "credentials")
25    ),
26    grpc.ClientCallDetails,
27):
28    pass
29
30
31def header_adder_interceptor(header, value):
32    def intercept_call(
33        client_call_details,
34        request_iterator,
35        request_streaming,
36        response_streaming,
37    ):
38        metadata = []
39        if client_call_details.metadata is not None:
40            metadata = list(client_call_details.metadata)
41        metadata.append(
42            (
43                header,
44                value,
45            )
46        )
47        client_call_details = _ClientCallDetails(
48            client_call_details.method,
49            client_call_details.timeout,
50            metadata,
51            client_call_details.credentials,
52        )
53        return client_call_details, request_iterator, None
54
55    return generic_client_interceptor.create(intercept_call)
56