Python client library for Google Cloud Platform services including Datastore, Storage, and Pub/Sub
npx @tessl/cli install tessl/pypi-gcloud@0.7.0A Python client library for Google Cloud Platform services, providing idiomatic Python interfaces for Google Cloud Datastore, Storage, and Pub/Sub. The library offers high-level abstractions over REST APIs with built-in authentication, connection management, and efficient batch operations.
pip install gcloudgoogle-apitools, httplib2, oauth2client, protobuf, pycrypto, pytz, siximport gcloudService-specific imports:
from gcloud import datastore
from gcloud import storage
from gcloud import pubsubfrom gcloud import datastore, storage, pubsub
# Datastore - NoSQL document database
client = datastore.Client(dataset_id='my-project')
key = client.key('Person', 'alice')
entity = datastore.Entity(key)
entity['name'] = 'Alice'
entity['age'] = 30
client.put(entity)
# Storage - Object storage
client = storage.Client(project='my-project')
bucket = client.get_bucket('my-bucket')
blob = storage.Blob('path/to/file.txt', bucket)
blob.upload_from_string('Hello, World!')
# Pub/Sub - Messaging service
client = pubsub.Client(project='my-project')
topic = client.topic('my-topic')
topic.create()
topic.publish('Hello, Pub/Sub!')The library follows a consistent client-based architecture across all services:
Credential management functions for OAuth2 authentication with Google Cloud services.
def get_credentials():
"""
Get credentials implicitly from current environment.
Returns:
OAuth2Credentials: Credentials for API access
"""
def get_for_service_account_json(json_credentials_path, scope=None):
"""
Get credentials from service account JSON file.
Parameters:
- json_credentials_path (str): Path to JSON credentials file
- scope (str|list): OAuth2 scopes
Returns:
OAuth2Credentials: Service account credentials
"""
def get_for_service_account_p12(client_email, private_key_path, scope=None):
"""
Get credentials from service account P12 file.
Parameters:
- client_email (str): Service account email
- private_key_path (str): Path to P12 private key file
- scope (str|list): OAuth2 scopes
Returns:
OAuth2Credentials: Service account credentials
"""
def generate_signed_url(credentials, resource, expiration, method='GET', **kwargs):
"""
Generate signed URL for Cloud Storage resource.
Parameters:
- credentials: OAuth2 credentials
- resource (str): Cloud Storage resource path
- expiration (datetime): URL expiration time
- method (str): HTTP method
Returns:
str: Signed URL
"""NoSQL document database service for storing and querying structured data. Provides entity management, querying, transactions, and batch operations with automatic scaling.
class Client:
def __init__(self, dataset_id=None, namespace=None, connection=None): ...
def get(self, key, missing=None, deferred=None): ...
def get_multi(self, keys, missing=None, deferred=None): ...
def put(self, entity): ...
def put_multi(self, entities): ...
def delete(self, key): ...
def delete_multi(self, keys): ...
def allocate_ids(self, incomplete_key, num_ids): ...
def key(self, *path_args, **kwargs): ...
def batch(self): ...
def query(self, **kwargs): ...
def transaction(self): ...
@property
def current_batch(self): ...
@property
def current_transaction(self): ...
class Entity(dict):
def __init__(self, key=None, exclude_from_indexes=()): ...
class Key:
def __init__(self, *path_args, **kwargs): ...
def completed_key(self, id_or_name): ...Object storage service for storing and retrieving files of any size. Provides bucket management, blob operations, access control, and metadata handling with support for large file uploads/downloads.
class Client:
def __init__(self, project=None, credentials=None, http=None): ...
def get_bucket(self, bucket_name): ...
def lookup_bucket(self, bucket_name): ...
def create_bucket(self, bucket_name): ...
def list_buckets(self, max_results=None, page_token=None, prefix=None, projection='noAcl', fields=None): ...
@property
def current_batch(self): ...
@property
def connection(self): ...
class Bucket:
def get_blob(self, blob_name, client=None): ...
def upload_file(self, filename, blob_name=None, client=None): ...
def list_blobs(self, max_results=None, page_token=None, prefix=None): ...
class Blob:
def download_as_string(self, client=None): ...
def upload_from_string(self, data, content_type='text/plain', client=None): ...Messaging service for asynchronous communication between applications. Provides topic-based publish/subscribe messaging with support for push and pull subscriptions.
class Client:
def __init__(self, project=None, credentials=None, http=None): ...
def list_topics(self, page_size=None, page_token=None): ...
def list_subscriptions(self, page_size=None, page_token=None, topic_name=None): ...
def topic(self, name, timestamp_messages=False): ...
class Topic:
def create(self, client=None): ...
def publish(self, message, client=None, **attrs): ...
def subscription(self, name, ack_deadline=None, push_endpoint=None): ...
class Subscription:
def pull(self, return_immediately=False, max_messages=1, client=None): ...
def acknowledge(self, ack_ids, client=None): ...
class Message:
def __init__(self, data, message_id, attributes=None): ...
@property
def attributes(self): ...
@property
def timestamp(self): ...
@classmethod
def from_api_repr(cls, api_repr): ...# Base client and connection types
class Client:
"""Base client for Google Cloud services."""
def __init__(self, credentials=None, http=None): ...
@classmethod
def from_service_account_json(cls, json_credentials_path, *args, **kwargs): ...
class JSONClient(Client):
"""Client for JSON-based Google Cloud APIs."""
def __init__(self, project=None, credentials=None, http=None): ...
class Connection:
"""Base connection class for Google Cloud APIs."""
def __init__(self, credentials=None, http=None): ...
@classmethod
def from_environment(cls): ...
def http_request(self, method, url, headers=None, data=None): ...
# Iterator for paginated results
class Iterator:
"""Generic iterator for paginated API responses."""
def __init__(self, client, extra_params=None): ...
def get_items_from_response(self, response): ...
def __iter__(self): ...
def __next__(self): ...
# Exception hierarchy
class GCloudError(Exception):
"""Base error class for gcloud errors."""
def __init__(self, message, errors=()): ...
@property
def errors(self): ...
class Redirection(GCloudError):
"""Base for 3xx redirects."""
...
class MovedPermanently(Redirection): ... # 301 errors
class NotModified(Redirection): ... # 304 errors
class TemporaryRedirect(Redirection): ... # 307 errors
class ResumeIncomplete(Redirection): ... # 308 errors
class ClientError(GCloudError):
"""Base for 4xx client errors."""
...
class BadRequest(ClientError): ... # 400 errors
class Unauthorized(ClientError): ... # 401 errors
class Forbidden(ClientError): ... # 403 errors
class NotFound(ClientError): ... # 404 errors
class MethodNotAllowed(ClientError): ... # 405 errors
class Conflict(ClientError): ... # 409 errors
class LengthRequired(ClientError): ... # 411 errors
class PreconditionFailed(ClientError): ... # 412 errors
class RequestRangeNotSatisfiable(ClientError): ... # 416 errors
class TooManyRequests(ClientError): ... # 429 errors
class ServerError(GCloudError):
"""Base for 5xx server errors."""
...
class InternalServerError(ServerError): ... # 500 errors
class NotImplemented(ServerError): ... # 501 errors
class ServiceUnavailable(ServerError): ... # 503 errors
# Exception factory function
def make_exception(response, content, error_info=None, use_json=True):
"""
Factory for creating exceptions based on HTTP response.
Parameters:
- response: HTTP response object with status attribute
- content (str|dict): Response body
- error_info (str): Optional extra error information
- use_json (bool): Whether content is JSON
Returns:
GCloudError: Exception specific to the response
"""