google.auth.transport.requests module

Transport adapter for Requests.

class TimeoutGuard(timeout, timeout_error_type=<class 'requests.exceptions.Timeout'>)[source]

Bases: object

A context manager raising an error if the suite execution took too long.

Parameters:
  • timeout (Union, Unionfloat, Tuplefloat, float) – The maximum number of seconds a suite can run without the context manager raising a timeout exception on exit. If passed as a tuple, the smaller of the values is taken as a timeout. If None, a timeout error is never raised.

  • timeout_error_type (OptionalException) – The type of the error to raise on timeout. Defaults to requests.exceptions.Timeout.

class Request(session=None)[source]

Bases: Request

Requests request adapter.

This class is used internally for making requests using various transports in a consistent way. If you use AuthorizedSession you do not need to construct or use this class directly.

This class can be useful if you want to manually refresh a Credentials instance:

import google.auth.transport.requests
import requests

request = google.auth.transport.requests.Request()

credentials.refresh(request)
Parameters:

session (requests.Session) – An instance requests.Session used to make HTTP requests. If not specified, a session will be created.

__call__(url, method='GET', body=None, headers=None, timeout=120, **kwargs)[source]

Make an HTTP request using requests.

Parameters:
  • url (str) – The URI to be requested.

  • method (str) – The HTTP method to use for the request. Defaults to ‘GET’.

  • body (bytes) – The payload or body in HTTP request.

  • headers (Mappingstr, str) – Request headers.

  • timeout (Optionalint) – The number of seconds to wait for a response from the server. If not specified or if None, the requests default timeout will be used.

  • kwargs – Additional arguments passed through to the underlying requests request() method.

Returns:

The HTTP response.

Return type:

google.auth.transport.Response

Raises:

google.auth.exceptions.TransportError – If any exception occurred.

class AuthorizedSession(credentials, refresh_status_codes=(HTTPStatus.UNAUTHORIZED,), max_refresh_attempts=2, refresh_timeout=None, auth_request=None, default_host=None)[source]

Bases: Session

A Requests Session class with credentials.

This class is used to perform requests to API endpoints that require authorization:

from google.auth.transport.requests import AuthorizedSession

authed_session = AuthorizedSession(credentials)

response = authed_session.request(
    'GET', 'https://www.googleapis.com/storage/v1/b')

The underlying request() implementation handles adding the credentials’ headers to the request and refreshing credentials as needed.

This class also supports mutual TLS via configure_mtls_channel() method. In order to use this method, the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable must be explicitly set to true, otherwise it does nothing. Assume the environment is set to true, the method behaves in the following manner:

If client_cert_callback is provided, client certificate and private key are loaded using the callback; if client_cert_callback is None, application default SSL credentials will be used. Exceptions are raised if there are problems with the certificate, private key, or the loading process, so it should be called within a try/except block.

First we set the environment variable to true, then create an AuthorizedSession instance and specify the endpoints:

regular_endpoint = 'https://pubsub.googleapis.com/v1/projects/{my_project_id}/topics'
mtls_endpoint = 'https://pubsub.mtls.googleapis.com/v1/projects/{my_project_id}/topics'

authed_session = AuthorizedSession(credentials)

Now we can pass a callback to configure_mtls_channel():

def my_cert_callback():
    # some code to load client cert bytes and private key bytes, both in
    # PEM format.
    some_code_to_load_client_cert_and_key()
    if loaded:
        return cert, key
    raise MyClientCertFailureException()

# Always call configure_mtls_channel within a try/except block.
try:
    authed_session.configure_mtls_channel(my_cert_callback)
except:
    # handle exceptions.

if authed_session.is_mtls:
    response = authed_session.request('GET', mtls_endpoint)
else:
    response = authed_session.request('GET', regular_endpoint)

You can alternatively use application default SSL credentials like this:

try:
    authed_session.configure_mtls_channel()
except:
    # handle exceptions.
Parameters:
  • credentials (google.auth.credentials.Credentials) – The credentials to add to the request.

  • refresh_status_codes (Sequenceint) – Which HTTP status codes indicate that credentials should be refreshed and the request should be retried.

  • max_refresh_attempts (int) – The maximum number of times to attempt to refresh the credentials and retry the request.

  • refresh_timeout (Optionalint) – The timeout value in seconds for credential refresh HTTP requests.

  • auth_request (google.auth.transport.requests.Request) – (Optional) An instance of Request used when refreshing credentials. If not passed, an instance of Request is created.

  • default_host (Optionalstr) – A host like “pubsub.googleapis.com”. This is used when a self-signed JWT is created from service account credentials.

configure_mtls_channel(client_cert_callback=None)[source]

Configure the client certificate and key for SSL connection.

The function does nothing unless GOOGLE_API_USE_CLIENT_CERTIFICATE is explicitly set to true. In this case if client certificate and key are successfully obtained (from the given client_cert_callback or from application default SSL credentials), a _MutualTlsAdapter instance will be mounted to “https://” prefix.

Parameters:

client_cert_callback (OptionalCallable, bytes, bytes) – The optional callback returns the client certificate and private key bytes both in PEM format. If the callback is None, application default SSL credentials will be used.

Raises:

google.auth.exceptions.MutualTLSChannelError – If mutual TLS channel creation failed for any reason.

request(method, url, data=None, headers=None, max_allowed_time=None, timeout=120, **kwargs)[source]

Implementation of Requests’ request.

Parameters:
  • timeout (OptionalUnionfloat, Tuplefloat, float) – The amount of time in seconds to wait for the server response with each individual request. Can also be passed as a tuple (connect_timeout, read_timeout). See requests.Session.request() documentation for details.

  • max_allowed_time (Optionalfloat) –

    If the method runs longer than this, a Timeout exception is automatically raised. Unlike the timeout parameter, this value applies to the total method execution time, even if multiple requests are made under the hood.

    Mind that it is not guaranteed that the timeout error is raised at max_allowed_time. It might take longer, for example, if an underlying request takes a lot of time, but the request itself does not timeout, e.g. if a large file is being transmitted. The timout error will be raised after such request completes.

property is_mtls

Indicates if the created SSL channel is mutual TLS.

close()[source]

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

Return type:

requests.adapters.BaseAdapter

get_redirect_target(resp)

Receives a Response. Returns a redirect URI or None

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

merge_environment_settings(url, proxies, stream, verify, cert)

Check the environment and merge it with some settings.

Return type:

dict

mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by prefix length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

post(url, data=None, json=None, **kwargs)

Sends a POST request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session.

Parameters:

requestRequest instance to prepare with this session’s settings.

Return type:

requests.PreparedRequest

put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).

This method also replaces the Proxy-Authorization header where necessary.

Return type:

dict

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

Receives a Response. Returns a generator of Responses or Requests.

send(request, **kwargs)

Send a given PreparedRequest.

Return type:

requests.Response

should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting

headers

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

auth

Default Authentication tuple or object to attach to Request.

proxies

Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request.

hooks

Event-handling hooks.

params

Dictionary of querystring data to attach to each Request. The dictionary values may be lists for representing multivalued query parameters.

stream

Stream response content default.

verify

SSL Verification default. Defaults to True, requiring requests to verify the TLS certificate at the remote end. If verify is set to False, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to False for testing.

cert

SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

max_redirects

Maximum number of redirects allowed. If the request exceeds this limit, a TooManyRedirects exception is raised. This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is 30.

trust_env

Trust environment settings for proxy configuration, default authentication and similar.

cookies

A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJar compatible object.