Shared Core Modules#

Base Client#

Base classes for client used to interact with Google Cloud APIs.

class google.cloud.client.Client(credentials=None, _http=None)[source]#

Bases: google.cloud.client._ClientFactoryMixin

Client to bundle configuration needed for API requests.

Stores credentials and an HTTP object so that subclasses can pass them along to a connection class.

If no value is passed in for _http, a httplib2.Http object will be created and authorized with the credentials. If not, the credentials and _http need not be related.

Callers and subclasses may seek to use the private key from credentials to sign data.

A custom (non-httplib2) HTTP object must have a request method which accepts the following arguments:

  • uri
  • method
  • body
  • headers

In addition, redirections and connection_type may be used.

A custom _http object will also need to be able to add a bearer token to API requests and handle token refresh on 401 errors.

Parameters:
  • credentials (Credentials) – (Optional) The OAuth2 Credentials to use for this client. If not passed (and if no _http object is passed), falls back to the default inferred from the environment.
  • _http (Http) – (Optional) HTTP object to make requests. Can be any object that defines request() with the same interface as request(). If not passed, an _http object is created that is bound to the credentials for the current object. This parameter should be considered private, and could change in the future.
SCOPE = None#

The scopes required for authenticating with a service.

Needs to be set by subclasses.

from_service_account_json(json_credentials_path, *args, **kwargs)#

Factory to retrieve JSON credentials while creating client.

Parameters:
  • json_credentials_path (str) – The path to a private key file (this file was given to you when you created the service account). This file must contain a JSON object with a private key and other credentials information (downloaded from the Google APIs console).
  • args (tuple) – Remaining positional arguments to pass to constructor.
  • kwargs (dict) – Remaining keyword arguments to pass to constructor.
Return type:

google.cloud.pubsub.client.Client

Returns:

The client created with the retrieved JSON credentials.

Raises:

TypeError if there is a conflict with the kwargs and the credentials created by the factory.

class google.cloud.client.ClientWithProject(project=None, credentials=None, _http=None)[source]#

Bases: google.cloud.client.Client, google.cloud.client._ClientProjectMixin

Client that also stores a project.

Parameters:
  • project (str) – the project which the client acts on behalf of. If not passed falls back to the default inferred from the environment.
  • credentials (Credentials) – (Optional) The OAuth2 Credentials to use for this client. If not passed (and if no _http object is passed), falls back to the default inferred from the environment.
  • _http (Http) – (Optional) HTTP object to make requests. Can be any object that defines request() with the same interface as request(). If not passed, an _http object is created that is bound to the credentials for the current object. This parameter should be considered private, and could change in the future.
Raises:

ValueError if the project is neither passed in nor set in the environment.

from_service_account_json(json_credentials_path, *args, **kwargs)#

Factory to retrieve JSON credentials while creating client.

Parameters:
  • json_credentials_path (str) – The path to a private key file (this file was given to you when you created the service account). This file must contain a JSON object with a private key and other credentials information (downloaded from the Google APIs console).
  • args (tuple) – Remaining positional arguments to pass to constructor.
  • kwargs (dict) – Remaining keyword arguments to pass to constructor.
Return type:

google.cloud.pubsub.client.Client

Returns:

The client created with the retrieved JSON credentials.

Raises:

TypeError if there is a conflict with the kwargs and the credentials created by the factory.

Credentials Helpers#

A simple wrapper around the OAuth2 credentials library.

google.cloud.credentials.generate_signed_url(credentials, resource, expiration, api_access_endpoint='', method='GET', content_md5=None, content_type=None, response_type=None, response_disposition=None, generation=None)[source]#

Generate signed URL to provide query-string auth’n to a resource.

Note

Assumes credentials implements the google.auth.credentials.Signing interface. Also assumes credentials has a service_account_email property which identifies the credentials.

Note

If you are on Google Compute Engine, you can’t generate a signed URL. Follow Issue 922 for updates on this. If you’d like to be able to generate a signed URL from GCE, you can use a standard service account from a JSON file rather than a GCE service account.

See headers reference for more details on optional arguments.

Parameters:
  • credentials (google.auth.credentials.Signing) – Credentials object with an associated private key to sign text.
  • resource (str) – A pointer to a specific resource (typically, /bucket-name/path/to/blob.txt).
  • expiration (int, long, datetime.datetime, datetime.timedelta) – When the signed URL should expire.
  • api_access_endpoint (str) – Optional URI base. Defaults to empty string.
  • method (str) – The HTTP verb that will be used when requesting the URL. Defaults to 'GET'.
  • content_md5 (str) – (Optional) The MD5 hash of the object referenced by resource.
  • content_type (str) – (Optional) The content type of the object referenced by resource.
  • response_type (str) – (Optional) Content type of responses to requests for the signed URL. Used to over-ride the content type of the underlying resource.
  • response_disposition (str) – (Optional) Content disposition of responses to requests for the signed URL.
  • generation (str) – (Optional) A value that indicates which generation of the resource to fetch.
Return type:

str

Returns:

A signed URL you can use to access the resource until expiration.

google.cloud.credentials.get_credentials()[source]#

Gets credentials implicitly from the current environment.

Uses google.auth.default().

Return type:google.auth.credentials.Credentials,
Returns:A new credentials instance corresponding to the implicit environment.

Exceptions#

Custom exceptions for google.cloud package.

See: https://cloud.google.com/storage/docs/json_api/v1/status-codes

exception google.cloud.exceptions.BadGateway(message, errors=())[source]#

Bases: google.cloud.exceptions.ServerError

Exception mapping a ‘502 Bad Gateway’ response.

exception google.cloud.exceptions.BadRequest(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘400 Bad Request’ response.

exception google.cloud.exceptions.ClientError(message, errors=())[source]#

Bases: google.cloud.exceptions.GoogleCloudError

Base for 4xx responses

This class is abstract

exception google.cloud.exceptions.Conflict(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘409 Conflict’ response.

exception google.cloud.exceptions.Forbidden(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘403 Forbidden’ response.

exception google.cloud.exceptions.GatewayTimeout(message, errors=())[source]#

Bases: google.cloud.exceptions.ServerError

Exception mapping a 504 Gateway Timeout’ response.

exception google.cloud.exceptions.GoogleCloudError(message, errors=())[source]#

Bases: exceptions.Exception

Base error class for Google Cloud errors (abstract).

Each subclass represents a single type of HTTP error response.

code = None#

HTTP status code. Concrete subclasses must define.

See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

errors#

Detailed error information.

Return type:list(dict)
Returns:a list of mappings describing each error.
google.cloud.exceptions.GrpcRendezvous#

Exception class raised by gRPC stable.

alias of _Rendezvous

exception google.cloud.exceptions.InternalServerError(message, errors=())[source]#

Bases: google.cloud.exceptions.ServerError

Exception mapping a ‘500 Internal Server Error’ response.

exception google.cloud.exceptions.LengthRequired(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘411 Length Required’ response.

exception google.cloud.exceptions.MethodNotAllowed(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘405 Method Not Allowed’ response.

exception google.cloud.exceptions.MethodNotImplemented(message, errors=())[source]#

Bases: google.cloud.exceptions.ServerError

Exception mapping a ‘501 Not Implemented’ response.

exception google.cloud.exceptions.MovedPermanently(message, errors=())[source]#

Bases: google.cloud.exceptions.Redirection

Exception mapping a ‘301 Moved Permanently’ response.

exception google.cloud.exceptions.NotFound(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘404 Not Found’ response.

exception google.cloud.exceptions.NotModified(message, errors=())[source]#

Bases: google.cloud.exceptions.Redirection

Exception mapping a ‘304 Not Modified’ response.

exception google.cloud.exceptions.PreconditionFailed(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘412 Precondition Failed’ response.

exception google.cloud.exceptions.Redirection(message, errors=())[source]#

Bases: google.cloud.exceptions.GoogleCloudError

Base for 3xx responses

This class is abstract.

exception google.cloud.exceptions.RequestRangeNotSatisfiable(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘416 Request Range Not Satisfiable’ response.

exception google.cloud.exceptions.ResumeIncomplete(message, errors=())[source]#

Bases: google.cloud.exceptions.Redirection

Exception mapping a ‘308 Resume Incomplete’ response.

exception google.cloud.exceptions.ServerError(message, errors=())[source]#

Bases: google.cloud.exceptions.GoogleCloudError

Base for 5xx responses: (abstract)

exception google.cloud.exceptions.ServiceUnavailable(message, errors=())[source]#

Bases: google.cloud.exceptions.ServerError

Exception mapping a ‘503 Service Unavailable’ response.

exception google.cloud.exceptions.TemporaryRedirect(message, errors=())[source]#

Bases: google.cloud.exceptions.Redirection

Exception mapping a ‘307 Temporary Redirect’ response.

exception google.cloud.exceptions.TooManyRequests(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘429 Too Many Requests’ response.

exception google.cloud.exceptions.Unauthorized(message, errors=())[source]#

Bases: google.cloud.exceptions.ClientError

Exception mapping a ‘401 Unauthorized’ response.

google.cloud.exceptions.make_exception(response, content, error_info=None, use_json=True)[source]#

Factory: create exception based on HTTP response code.

Parameters:
  • response (httplib2.Response or other HTTP response object) – A response object that defines a status code as the status attribute.
  • content (str or dictionary) – The body of the HTTP error response.
  • error_info (str) – Optional string giving extra information about the failed request.
  • use_json (bool) – Flag indicating if content is expected to be JSON.
Return type:

instance of GoogleCloudError, or a concrete subclass.

Returns:

Exception specific to the error response.

Environment Variables#

Comprehensive list of environment variables used in google-cloud.

These enable many types of implicit behavior in both production and tests.

google.cloud.environment_vars.BIGTABLE_EMULATOR = 'BIGTABLE_EMULATOR_HOST'#

Environment variable defining host for Bigtable emulator.

google.cloud.environment_vars.DISABLE_GRPC = 'GOOGLE_CLOUD_DISABLE_GRPC'#

Environment variable acting as flag to disable gRPC.

To be used for APIs where both an HTTP and gRPC implementation exist.

google.cloud.environment_vars.GCD_DATASET = 'DATASTORE_DATASET'#

Environment variable defining default dataset ID under GCD.

google.cloud.environment_vars.GCD_HOST = 'DATASTORE_EMULATOR_HOST'#

Environment variable defining host for GCD dataset server.

google.cloud.environment_vars.PUBSUB_EMULATOR = 'PUBSUB_EMULATOR_HOST'#

Environment variable defining host for Pub/Sub emulator.

IAM Support#

Non-API-specific IAM policy definitions

For allowed roles / permissions, see: https://cloud.google.com/iam/docs/understanding-roles

google.cloud.iam.EDITOR_ROLE = 'roles/editor'#

Generic role implying rights to modify an object.

google.cloud.iam.OWNER_ROLE = 'roles/owner'#

Generic role implying all rights to an object.

class google.cloud.iam.Policy(etag=None, version=None)[source]#

Bases: _abcoll.MutableMapping

IAM Policy

See: https://cloud.google.com/iam/reference/rest/v1/Policy

Parameters:
  • etag (str) – ETag used to identify a unique of the policy
  • version (int) – unique version of the policy
static all_users()[source]#

Factory method for a member representing all users.

Return type:str
Returns:A member string representing all users.
static authenticated_users()[source]#

Factory method for a member representing all authenticated users.

Return type:str
Returns:A member string representing all authenticated users.
static domain(domain)[source]#

Factory method for a domain member.

Parameters:domain (str) – The domain for this member.
Return type:str
Returns:A member string corresponding to the given domain.
editors#

Legacy access to editor role.

classmethod from_api_repr(resource)[source]#

Create a policy from the resource returned from the API.

Parameters:resource (dict) – resource returned from the getIamPolicy API.
Return type:Policy
Returns:the parsed policy
static group(email)[source]#

Factory method for a group member.

Parameters:email (str) – An id or e-mail for this particular group.
Return type:str
Returns:A member string corresponding to the given group.
owners#

Legacy access to owner role.

static service_account(email)[source]#

Factory method for a service account member.

Parameters:email (str) – E-mail for this particular service account.
Return type:str
Returns:A member string corresponding to the given service account.
to_api_repr()[source]#

Construct a Policy resource.

Return type:dict
Returns:a resource to be passed to the setIamPolicy API.
static user(email)[source]#

Factory method for a user member.

Parameters:email (str) – E-mail for this particular user.
Return type:str
Returns:A member string corresponding to the given user.
viewers#

Legacy access to viewer role.

google.cloud.iam.VIEWER_ROLE = 'roles/viewer'#

Generic role implying rights to access an object.