google.auth.transport.urllib3 module¶
Transport adapter for urllib3.
-
class
Request
(http)[source]¶ Bases:
google.auth.transport.Request
urllib3 request adapter.
This class is used internally for making requests using various transports in a consistent way. If you use
AuthorizedHttp
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.urllib3 import urllib3 http = urllib3.PoolManager() request = google.auth.transport.urllib3.Request(http) credentials.refresh(request)
- Parameters
http (urllib3.request.RequestMethods) – An instance of any urllib3 class that implements
RequestMethods
, usuallyurllib3.PoolManager
.
-
__call__
(url, method='GET', body=None, headers=None, timeout=None, **kwargs)[source]¶ Make an HTTP request using urllib3.
- 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 / body in HTTP request.
timeout (
Optional
[int
]) – The number of seconds to wait for a response from the server. If not specified or if None, the urllib3 default timeout will be used.kwargs – Additional arguments passed throught to the underlying urllib3
urlopen()
method.
- Returns
The HTTP response.
- Return type
- Raises
google.auth.exceptions.TransportError – If any exception occurred.
-
class
AuthorizedHttp
(credentials, http=None, refresh_status_codes=(<HTTPStatus.UNAUTHORIZED: 401>, ), max_refresh_attempts=2)[source]¶ Bases:
urllib3.request.RequestMethods
A urllib3 HTTP class with credentials.
This class is used to perform requests to API endpoints that require authorization:
from google.auth.transport.urllib3 import AuthorizedHttp authed_http = AuthorizedHttp(credentials) response = authed_http.request( 'GET', 'https://www.googleapis.com/storage/v1/b')
This class implements
urllib3.request.RequestMethods
and can be used just like any otherurllib3.PoolManager
.The underlying
urlopen()
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. If client_cert_callabck is provided, client certificate and private key are loaded using the callback; if client_cert_callabck 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 create an
AuthorizedHttp
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_http = AuthorizedHttp(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: is_mtls = authed_http.configure_mtls_channel(my_cert_callback) except: # handle exceptions. if is_mtls: response = authed_http.request('GET', mtls_endpoint) else: response = authed_http.request('GET', regular_endpoint)
You can alternatively use application default SSL credentials like this:
try: is_mtls = authed_http.configure_mtls_channel() except: # handle exceptions.
- Parameters
credentials (google.auth.credentials.Credentials) – The credentials to add to the request.
http (urllib3.PoolManager) – The underlying HTTP object to use to make requests. If not specified, a
urllib3.PoolManager
instance will be constructed with sane defaults.refresh_status_codes (
Sequence
[int
]) – 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.
-
configure_mtls_channel
(client_cert_callabck=None)[source]¶ Configures mutual TLS channel using the given client_cert_callabck or application default SSL credentials. Returns True if the channel is mutual TLS and False otherwise. Note that the http provided in the constructor will be overwritten.
- Parameters
client_cert_callabck (
Optional
[Callable
[ ,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.- Returns
True if the channel is mutual TLS and False otherwise.
- Raises
google.auth.exceptions.MutualTLSChannelError – If mutual TLS channel creation failed for any reason.
-
urlopen
(method, url, body=None, headers=None, **kwargs)[source]¶ Implementation of urllib3’s urlopen.
-
request
(method, url, fields=None, headers=None, **urlopen_kw)¶ Make a request using
urlopen()
with the appropriate encoding offields
based on themethod
used.This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as
request_encode_url()
,request_encode_body()
, or even the lowest levelurlopen()
.
-
request_encode_body
(method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw)¶ Make a request using
urlopen()
with thefields
encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.When
encode_multipart=True
(default), thenurllib3.filepost.encode_multipart_formdata()
is used to encode the payload with the appropriate content type. Otherwiseurllib.urlencode()
is used with the ‘application/x-www-form-urlencoded’ content type.Multipart encoding must be used when posting files, and it’s reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth.
Supports an optional
fields
parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', }
When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers.
Note that if
headers
are supplied, the ‘Content-Type’ header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with themultipart_boundary
parameter.
-
request_encode_url
(method, url, fields=None, headers=None, **urlopen_kw)¶ Make a request using
urlopen()
with thefields
encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.
-
property
headers
¶ Proxy to
self.http
.