aboutsummaryrefslogtreecommitdiff
path: root/google/auth/transport/_http_client.py
blob: c153763efa2c68d3155f5a435112344a47e7914c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Transport adapter for http.client, for internal use only."""

import logging
import socket

import six
from six.moves import http_client
from six.moves import urllib

from google.auth import exceptions
from google.auth import transport

_LOGGER = logging.getLogger(__name__)


class Response(transport.Response):
    """http.client transport response adapter.

    Args:
        response (http.client.HTTPResponse): The raw http client response.
    """

    def __init__(self, response):
        self._status = response.status
        self._headers = {key.lower(): value for key, value in response.getheaders()}
        self._data = response.read()

    @property
    def status(self):
        return self._status

    @property
    def headers(self):
        return self._headers

    @property
    def data(self):
        return self._data


class Request(transport.Request):
    """http.client transport request adapter."""

    def __call__(
        self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
    ):
        """Make an HTTP request using http.client.

        Args:
            url (str): The URI to be requested.
            method (str): The HTTP method to use for the request. Defaults
                to 'GET'.
            body (bytes): The payload / body in HTTP request.
            headers (Mapping): Request headers.
            timeout (Optional(int)): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                socket global default timeout will be used.
            kwargs: Additional arguments passed throught to the underlying
                :meth:`~http.client.HTTPConnection.request` method.

        Returns:
            Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """
        # socket._GLOBAL_DEFAULT_TIMEOUT is the default in http.client.
        if timeout is None:
            timeout = socket._GLOBAL_DEFAULT_TIMEOUT

        # http.client doesn't allow None as the headers argument.
        if headers is None:
            headers = {}

        # http.client needs the host and path parts specified separately.
        parts = urllib.parse.urlsplit(url)
        path = urllib.parse.urlunsplit(
            ("", "", parts.path, parts.query, parts.fragment)
        )

        if parts.scheme != "http":
            raise exceptions.TransportError(
                "http.client transport only supports the http scheme, {}"
                "was specified".format(parts.scheme)
            )

        connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)

        try:
            _LOGGER.debug("Making request: %s %s", method, url)

            connection.request(method, path, body=body, headers=headers, **kwargs)
            response = connection.getresponse()
            return Response(response)

        except (http_client.HTTPException, socket.error) as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc)

        finally:
            connection.close()