|
| 1 | +# Copyright 2016 Google Inc. |
| 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 | + |
| 15 | +"""Transport adapter for Requests.""" |
| 16 | + |
| 17 | +from __future__ import absolute_import |
| 18 | + |
| 19 | +import logging |
| 20 | + |
| 21 | + |
| 22 | +import requests |
| 23 | +import requests.exceptions |
| 24 | + |
| 25 | +from google.auth import exceptions |
| 26 | +from google.auth import transport |
| 27 | + |
| 28 | +_LOGGER = logging.getLogger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +class _Response(transport.Response): |
| 32 | + """Requests transport response adapter. |
| 33 | +
|
| 34 | + Args: |
| 35 | + response (requests.Response): The raw Requests response. |
| 36 | + """ |
| 37 | + def __init__(self, response): |
| 38 | + self._response = response |
| 39 | + |
| 40 | + @property |
| 41 | + def status(self): |
| 42 | + return self._response.status_code |
| 43 | + |
| 44 | + @property |
| 45 | + def headers(self): |
| 46 | + return self._response.headers |
| 47 | + |
| 48 | + @property |
| 49 | + def data(self): |
| 50 | + return self._response.content |
| 51 | + |
| 52 | + |
| 53 | +class Request(transport.Request): |
| 54 | + """Requests request adapter. |
| 55 | +
|
| 56 | + This class is used internally for making requests using various transports |
| 57 | + in a consistent way. If you use :class:`AuthorizedSession` you do not need |
| 58 | + to construct or use this class directly. |
| 59 | +
|
| 60 | + This class can be useful if you want to manually refresh a |
| 61 | + :class:`~google.auth.credentials.Credentials` instance:: |
| 62 | +
|
| 63 | + import google.auth.transport.requests |
| 64 | + import requests |
| 65 | +
|
| 66 | + request = google.auth.transport.requests.Request() |
| 67 | +
|
| 68 | + credentials.refresh(request) |
| 69 | +
|
| 70 | + Args: |
| 71 | + session (requests.Session): An instance :class:`requests.Session` used |
| 72 | + to make HTTP requests. If not specified, a session will be created. |
| 73 | +
|
| 74 | + .. automethod:: __call__ |
| 75 | + """ |
| 76 | + def __init__(self, session=None): |
| 77 | + if not session: |
| 78 | + session = requests.Session() |
| 79 | + |
| 80 | + self.session = session |
| 81 | + |
| 82 | + def __call__(self, url, method='GET', body=None, headers=None, |
| 83 | + timeout=None, **kwargs): |
| 84 | + """Make an HTTP request using requests. |
| 85 | +
|
| 86 | + Args: |
| 87 | + url (str): The URI to be requested. |
| 88 | + method (str): The HTTP method to use for the request. Defaults |
| 89 | + to 'GET'. |
| 90 | + body (bytes): The payload / body in HTTP request. |
| 91 | + headers (Mapping[str, str]): Request headers. |
| 92 | + timeout (Optional[int]): The number of seconds to wait for a |
| 93 | + response from the server. If not specified or if None, the |
| 94 | + requests default timeout will be used. |
| 95 | + kwargs: Additional arguments passed through to the underlying |
| 96 | + requests :meth:`~requests.Session.request` method. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + google.auth.transport.Response: The HTTP response. |
| 100 | +
|
| 101 | + Raises: |
| 102 | + google.auth.exceptions.TransportError: If any exception occurred. |
| 103 | + """ |
| 104 | + try: |
| 105 | + _LOGGER.debug('Making request: %s %s', method, url) |
| 106 | + response = self.session.request( |
| 107 | + method, url, data=body, headers=headers, timeout=timeout, |
| 108 | + **kwargs) |
| 109 | + return _Response(response) |
| 110 | + except requests.exceptions.RequestException as exc: |
| 111 | + raise exceptions.TransportError(exc) |
| 112 | + |
| 113 | + |
| 114 | +class AuthorizedSession(requests.Session): |
| 115 | + """A Requests Session class with credentials. |
| 116 | +
|
| 117 | + This class is used to perform requests to API endpoints that require |
| 118 | + authorization:: |
| 119 | +
|
| 120 | + from google.auth.transport.requests import AuthorizedSession |
| 121 | +
|
| 122 | + authed_session = AuthorizedSession(credentials) |
| 123 | +
|
| 124 | + response = authed_session.request( |
| 125 | + 'GET', 'https://www.googleapis.com/storage/v1/b') |
| 126 | +
|
| 127 | + The underlying :meth:`request` implementation handles adding the |
| 128 | + credentials' headers to the request and refreshing credentials as needed. |
| 129 | +
|
| 130 | + Args: |
| 131 | + credentials (google.auth.credentials.Credentials): The credentials to |
| 132 | + add to the request. |
| 133 | + refresh_status_codes (Sequence[int]): Which HTTP status codes indicate |
| 134 | + that credentials should be refreshed and the request should be |
| 135 | + retried. |
| 136 | + max_refresh_attempts (int): The maximum number of times to attempt to |
| 137 | + refresh the credentials and retry the request. |
| 138 | + kwargs: Additional arguments passed to the :class:`requests.Session` |
| 139 | + constructor. |
| 140 | + """ |
| 141 | + def __init__(self, credentials, |
| 142 | + refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES, |
| 143 | + max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS, |
| 144 | + **kwargs): |
| 145 | + super(AuthorizedSession, self).__init__(**kwargs) |
| 146 | + self.credentials = credentials |
| 147 | + self._refresh_status_codes = refresh_status_codes |
| 148 | + self._max_refresh_attempts = max_refresh_attempts |
| 149 | + # Request instance used by internal methods (for example, |
| 150 | + # credentials.refresh). |
| 151 | + # Do not pass `self` as the session here, as it can lead to infinite |
| 152 | + # recursion. |
| 153 | + self._auth_request = Request() |
| 154 | + |
| 155 | + def request(self, method, url, data=None, headers=None, **kwargs): |
| 156 | + """Implementation of Requests' request.""" |
| 157 | + |
| 158 | + # Use a kwarg for this instead of an attribute to maintain |
| 159 | + # thread-safety. |
| 160 | + _credential_refresh_attempt = kwargs.pop( |
| 161 | + '_credential_refresh_attempt', 0) |
| 162 | + |
| 163 | + # Make a copy of the headers. They will be modified by the credentials |
| 164 | + # and we want to pass the original headers if we recurse. |
| 165 | + request_headers = headers.copy() if headers is not None else {} |
| 166 | + |
| 167 | + self.credentials.before_request( |
| 168 | + self._auth_request, method, url, request_headers) |
| 169 | + |
| 170 | + response = super(AuthorizedSession, self).request( |
| 171 | + method, url, data=data, headers=request_headers, **kwargs) |
| 172 | + |
| 173 | + # If the response indicated that the credentials needed to be |
| 174 | + # refreshed, then refresh the credentials and re-attempt the |
| 175 | + # request. |
| 176 | + # A stored token may expire between the time it is retrieved and |
| 177 | + # the time the request is made, so we may need to try twice. |
| 178 | + if (response.status_code in self._refresh_status_codes |
| 179 | + and _credential_refresh_attempt < self._max_refresh_attempts): |
| 180 | + |
| 181 | + _LOGGER.info( |
| 182 | + 'Refreshing credentials due to a %s response. Attempt %s/%s.', |
| 183 | + response.status_code, _credential_refresh_attempt + 1, |
| 184 | + self._max_refresh_attempts) |
| 185 | + |
| 186 | + self.credentials.refresh(self._auth_request) |
| 187 | + |
| 188 | + # Recurse. Pass in the original headers, not our modified set. |
| 189 | + return self.request( |
| 190 | + method, url, data=data, headers=headers, |
| 191 | + _credential_refresh_attempt=_credential_refresh_attempt + 1, |
| 192 | + **kwargs) |
| 193 | + |
| 194 | + return response |
0 commit comments