Python client library for Google Cloud Platform services including Datastore, Storage, and Pub/Sub
npx @tessl/cli install tessl/pypi-gcloud@0.7.00
# Google Cloud Python Client Library (gcloud)
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: gcloud
7
- **Language**: Python
8
- **Installation**: `pip install gcloud`
9
- **Dependencies**: `google-apitools`, `httplib2`, `oauth2client`, `protobuf`, `pycrypto`, `pytz`, `six`
10
11
## Core Imports
12
13
```python
14
import gcloud
15
```
16
17
Service-specific imports:
18
19
```python
20
from gcloud import datastore
21
from gcloud import storage
22
from gcloud import pubsub
23
```
24
25
## Basic Usage
26
27
```python
28
from gcloud import datastore, storage, pubsub
29
30
# Datastore - NoSQL document database
31
client = datastore.Client(dataset_id='my-project')
32
key = client.key('Person', 'alice')
33
entity = datastore.Entity(key)
34
entity['name'] = 'Alice'
35
entity['age'] = 30
36
client.put(entity)
37
38
# Storage - Object storage
39
client = storage.Client(project='my-project')
40
bucket = client.get_bucket('my-bucket')
41
blob = storage.Blob('path/to/file.txt', bucket)
42
blob.upload_from_string('Hello, World!')
43
44
# Pub/Sub - Messaging service
45
client = pubsub.Client(project='my-project')
46
topic = client.topic('my-topic')
47
topic.create()
48
topic.publish('Hello, Pub/Sub!')
49
```
50
51
## Architecture
52
53
The library follows a consistent client-based architecture across all services:
54
55
- **Client Classes**: Entry points for service configuration (credentials, project, HTTP transport)
56
- **Resource Hierarchy**: Logical organization (Client → Bucket → Blob for Storage)
57
- **Connection Management**: HTTP client handling with OAuth2 authentication
58
- **Batch Operations**: Efficient grouping of multiple operations
59
- **Context Managers**: Automatic resource management for transactions and batches
60
- **Exception Hierarchy**: HTTP status code based error handling
61
62
## Capabilities
63
64
### Authentication and Credentials
65
66
Credential management functions for OAuth2 authentication with Google Cloud services.
67
68
```python { .api }
69
def get_credentials():
70
"""
71
Get credentials implicitly from current environment.
72
73
Returns:
74
OAuth2Credentials: Credentials for API access
75
"""
76
77
def get_for_service_account_json(json_credentials_path, scope=None):
78
"""
79
Get credentials from service account JSON file.
80
81
Parameters:
82
- json_credentials_path (str): Path to JSON credentials file
83
- scope (str|list): OAuth2 scopes
84
85
Returns:
86
OAuth2Credentials: Service account credentials
87
"""
88
89
def get_for_service_account_p12(client_email, private_key_path, scope=None):
90
"""
91
Get credentials from service account P12 file.
92
93
Parameters:
94
- client_email (str): Service account email
95
- private_key_path (str): Path to P12 private key file
96
- scope (str|list): OAuth2 scopes
97
98
Returns:
99
OAuth2Credentials: Service account credentials
100
"""
101
102
def generate_signed_url(credentials, resource, expiration, method='GET', **kwargs):
103
"""
104
Generate signed URL for Cloud Storage resource.
105
106
Parameters:
107
- credentials: OAuth2 credentials
108
- resource (str): Cloud Storage resource path
109
- expiration (datetime): URL expiration time
110
- method (str): HTTP method
111
112
Returns:
113
str: Signed URL
114
"""
115
```
116
117
### Google Cloud Datastore
118
119
NoSQL document database service for storing and querying structured data. Provides entity management, querying, transactions, and batch operations with automatic scaling.
120
121
```python { .api }
122
class Client:
123
def __init__(self, dataset_id=None, namespace=None, connection=None): ...
124
def get(self, key, missing=None, deferred=None): ...
125
def get_multi(self, keys, missing=None, deferred=None): ...
126
def put(self, entity): ...
127
def put_multi(self, entities): ...
128
def delete(self, key): ...
129
def delete_multi(self, keys): ...
130
def allocate_ids(self, incomplete_key, num_ids): ...
131
def key(self, *path_args, **kwargs): ...
132
def batch(self): ...
133
def query(self, **kwargs): ...
134
def transaction(self): ...
135
@property
136
def current_batch(self): ...
137
@property
138
def current_transaction(self): ...
139
140
class Entity(dict):
141
def __init__(self, key=None, exclude_from_indexes=()): ...
142
143
class Key:
144
def __init__(self, *path_args, **kwargs): ...
145
def completed_key(self, id_or_name): ...
146
```
147
148
[Google Cloud Datastore](./datastore.md)
149
150
### Google Cloud Storage
151
152
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.
153
154
```python { .api }
155
class Client:
156
def __init__(self, project=None, credentials=None, http=None): ...
157
def get_bucket(self, bucket_name): ...
158
def lookup_bucket(self, bucket_name): ...
159
def create_bucket(self, bucket_name): ...
160
def list_buckets(self, max_results=None, page_token=None, prefix=None, projection='noAcl', fields=None): ...
161
@property
162
def current_batch(self): ...
163
@property
164
def connection(self): ...
165
166
class Bucket:
167
def get_blob(self, blob_name, client=None): ...
168
def upload_file(self, filename, blob_name=None, client=None): ...
169
def list_blobs(self, max_results=None, page_token=None, prefix=None): ...
170
171
class Blob:
172
def download_as_string(self, client=None): ...
173
def upload_from_string(self, data, content_type='text/plain', client=None): ...
174
```
175
176
[Google Cloud Storage](./storage.md)
177
178
### Google Cloud Pub/Sub
179
180
Messaging service for asynchronous communication between applications. Provides topic-based publish/subscribe messaging with support for push and pull subscriptions.
181
182
```python { .api }
183
class Client:
184
def __init__(self, project=None, credentials=None, http=None): ...
185
def list_topics(self, page_size=None, page_token=None): ...
186
def list_subscriptions(self, page_size=None, page_token=None, topic_name=None): ...
187
def topic(self, name, timestamp_messages=False): ...
188
189
class Topic:
190
def create(self, client=None): ...
191
def publish(self, message, client=None, **attrs): ...
192
def subscription(self, name, ack_deadline=None, push_endpoint=None): ...
193
194
class Subscription:
195
def pull(self, return_immediately=False, max_messages=1, client=None): ...
196
def acknowledge(self, ack_ids, client=None): ...
197
198
class Message:
199
def __init__(self, data, message_id, attributes=None): ...
200
@property
201
def attributes(self): ...
202
@property
203
def timestamp(self): ...
204
@classmethod
205
def from_api_repr(cls, api_repr): ...
206
```
207
208
[Google Cloud Pub/Sub](./pubsub.md)
209
210
## Types
211
212
```python { .api }
213
# Base client and connection types
214
class Client:
215
"""Base client for Google Cloud services."""
216
def __init__(self, credentials=None, http=None): ...
217
@classmethod
218
def from_service_account_json(cls, json_credentials_path, *args, **kwargs): ...
219
220
class JSONClient(Client):
221
"""Client for JSON-based Google Cloud APIs."""
222
def __init__(self, project=None, credentials=None, http=None): ...
223
224
class Connection:
225
"""Base connection class for Google Cloud APIs."""
226
def __init__(self, credentials=None, http=None): ...
227
@classmethod
228
def from_environment(cls): ...
229
def http_request(self, method, url, headers=None, data=None): ...
230
231
# Iterator for paginated results
232
class Iterator:
233
"""Generic iterator for paginated API responses."""
234
def __init__(self, client, extra_params=None): ...
235
def get_items_from_response(self, response): ...
236
def __iter__(self): ...
237
def __next__(self): ...
238
239
# Exception hierarchy
240
class GCloudError(Exception):
241
"""Base error class for gcloud errors."""
242
def __init__(self, message, errors=()): ...
243
@property
244
def errors(self): ...
245
246
class Redirection(GCloudError):
247
"""Base for 3xx redirects."""
248
...
249
250
class MovedPermanently(Redirection): ... # 301 errors
251
class NotModified(Redirection): ... # 304 errors
252
class TemporaryRedirect(Redirection): ... # 307 errors
253
class ResumeIncomplete(Redirection): ... # 308 errors
254
255
class ClientError(GCloudError):
256
"""Base for 4xx client errors."""
257
...
258
259
class BadRequest(ClientError): ... # 400 errors
260
class Unauthorized(ClientError): ... # 401 errors
261
class Forbidden(ClientError): ... # 403 errors
262
class NotFound(ClientError): ... # 404 errors
263
class MethodNotAllowed(ClientError): ... # 405 errors
264
class Conflict(ClientError): ... # 409 errors
265
class LengthRequired(ClientError): ... # 411 errors
266
class PreconditionFailed(ClientError): ... # 412 errors
267
class RequestRangeNotSatisfiable(ClientError): ... # 416 errors
268
class TooManyRequests(ClientError): ... # 429 errors
269
270
class ServerError(GCloudError):
271
"""Base for 5xx server errors."""
272
...
273
274
class InternalServerError(ServerError): ... # 500 errors
275
class NotImplemented(ServerError): ... # 501 errors
276
class ServiceUnavailable(ServerError): ... # 503 errors
277
278
# Exception factory function
279
def make_exception(response, content, error_info=None, use_json=True):
280
"""
281
Factory for creating exceptions based on HTTP response.
282
283
Parameters:
284
- response: HTTP response object with status attribute
285
- content (str|dict): Response body
286
- error_info (str): Optional extra error information
287
- use_json (bool): Whether content is JSON
288
289
Returns:
290
GCloudError: Exception specific to the response
291
"""
292
```