-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathsnippets.py
316 lines (244 loc) · 8.58 KB
/
snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Testable usage examples for Google Cloud Storage API wrapper
Each example function takes a ``client`` argument (which must be an instance
of :class:`google.cloud.storage.client.Client`) and uses it to perform a task
with the API.
To facilitate running the examples as system tests, each example is also passed
a ``to_delete`` list; the function adds to the list any objects created which
need to be deleted during teardown.
"""
from google.cloud import storage
def snippet(func):
"""Mark ``func`` as a snippet example function."""
func._snippet = True
return func
@snippet
def storage_get_started(to_delete):
# [START storage_get_started]
client = storage.Client()
bucket = client.get_bucket("bucket-id-here")
# Then do other things...
blob = bucket.get_blob("/remote/path/to/file.txt")
assert blob.download_as_string() == b"My old contents!"
blob.upload_from_string("New contents!")
blob2 = bucket.blob("/remote/path/storage.txt")
blob2.upload_from_filename(filename="/local/path.txt")
# [END storage_get_started]
to_delete.append(bucket)
@snippet
def client_bucket_acl(client, to_delete):
bucket_name = "system-test-bucket"
client.create_bucket(bucket_name)
# [START client_bucket_acl]
client = storage.Client()
bucket = client.get_bucket(bucket_name)
acl = bucket.acl
# [END client_bucket_acl]
to_delete.append(bucket)
# [START acl_user_settings]
acl.user("me@example.org").grant_read()
acl.all_authenticated().grant_write()
# [END acl_user_settings]
# [START acl_save]
acl.save()
# [END acl_save]
# [START acl_revoke_write]
acl.all().grant_read()
acl.all().revoke_write()
# [END acl_revoke_write]
# [START acl_save_bucket]
bucket.acl.save(acl=acl)
# [END acl_save_bucket]
# [START acl_print]
print(list(acl))
# [{'role': 'OWNER', 'entity': 'allUsers'}, ...]
# [END acl_print]
@snippet
def download_to_file(to_delete):
# [START download_to_file]
from google.cloud.storage import Blob
client = storage.Client(project="my-project")
bucket = client.get_bucket("my-bucket")
encryption_key = "c7f32af42e45e85b9848a6a14dd2a8f6"
blob = Blob("secure-data", bucket, encryption_key=encryption_key)
blob.upload_from_string("my secret message.")
with open("/tmp/my-secure-file", "wb") as file_obj:
blob.download_to_file(file_obj)
# [END download_to_file]
to_delete.append(blob)
@snippet
def upload_from_file(to_delete):
# [START upload_from_file]
from google.cloud.storage import Blob
client = storage.Client(project="my-project")
bucket = client.get_bucket("my-bucket")
encryption_key = "aa426195405adee2c8081bb9e7e74b19"
blob = Blob("secure-data", bucket, encryption_key=encryption_key)
with open("my-file", "rb") as my_file:
blob.upload_from_file(my_file)
# [END upload_from_file]
to_delete.append(blob)
@snippet
def get_blob(to_delete):
from google.cloud.storage.blob import Blob
# [START get_blob]
client = storage.Client()
bucket = client.get_bucket("my-bucket")
assert isinstance(bucket.get_blob("/path/to/blob.txt"), Blob)
# <Blob: my-bucket, /path/to/blob.txt>
assert not bucket.get_blob("/does-not-exist.txt")
# None
# [END get_blob]
to_delete.append(bucket)
@snippet
def delete_blob(to_delete):
# [START delete_blob]
from google.cloud.exceptions import NotFound
client = storage.Client()
bucket = client.get_bucket("my-bucket")
blobs = list(bucket.list_blobs())
assert len(blobs) > 0
# [<Blob: my-bucket, my-file.txt>]
bucket.delete_blob("my-file.txt")
try:
bucket.delete_blob("doesnt-exist")
except NotFound:
pass
# [END delete_blob]
blob = None
# [START delete_blobs]
bucket.delete_blobs([blob], on_error=lambda blob: None)
# [END delete_blobs]
to_delete.append(bucket)
@snippet
def configure_website(to_delete):
bucket_name = "test-bucket"
# [START configure_website]
client = storage.Client()
bucket = client.get_bucket(bucket_name)
bucket.configure_website("index.html", "404.html")
# [END configure_website]
# [START make_public]
bucket.make_public(recursive=True, future=True)
# [END make_public]
to_delete.append(bucket)
@snippet
def get_bucket(client, to_delete):
import google
# [START get_bucket]
try:
bucket = client.get_bucket("my-bucket")
except google.cloud.exceptions.NotFound:
print("Sorry, that bucket does not exist!")
# [END get_bucket]
to_delete.append(bucket)
@snippet
def add_lifecycle_delete_rule(client, to_delete):
# [START add_lifecycle_delete_rule]
bucket = client.get_bucket("my-bucket")
bucket.add_lifecycle_delete_rule(age=2)
bucket.patch()
# [END add_lifecycle_delete_rule]
to_delete.append(bucket)
@snippet
def add_lifecycle_set_storage_class_rule(client, to_delete):
# [START add_lifecycle_set_storage_class_rule]
bucket = client.get_bucket("my-bucket")
bucket.add_lifecycle_set_storage_class_rule(
"COLD_LINE", matches_storage_class=["NEARLINE"]
)
bucket.patch()
# [END add_lifecycle_set_storage_class_rule]
to_delete.append(bucket)
@snippet
def lookup_bucket(client, to_delete):
from google.cloud.storage.bucket import Bucket
# [START lookup_bucket]
bucket = client.lookup_bucket("doesnt-exist")
assert not bucket
# None
bucket = client.lookup_bucket("my-bucket")
assert isinstance(bucket, Bucket)
# <Bucket: my-bucket>
# [END lookup_bucket]
to_delete.append(bucket)
@snippet
def create_bucket(client, to_delete):
from google.cloud.storage import Bucket
# [START create_bucket]
bucket = client.create_bucket("my-bucket")
assert isinstance(bucket, Bucket)
# <Bucket: my-bucket>
# [END create_bucket]
to_delete.append(bucket)
@snippet
def list_buckets(client, to_delete):
# [START list_buckets]
for bucket in client.list_buckets():
print(bucket)
# [END list_buckets]
for bucket in client.list_buckets():
to_delete.append(bucket)
@snippet
def policy_document(client):
# pylint: disable=unused-argument
# [START policy_document]
bucket = client.bucket("my-bucket")
conditions = [["starts-with", "$key", ""], {"acl": "public-read"}]
policy = bucket.generate_upload_policy(conditions)
# Generate an upload form using the form fields.
policy_fields = "".join(
'<input type="hidden" name="{key}" value="{value}">'.format(
key=key, value=value
)
for key, value in policy.items()
)
upload_form = (
'<form action="http://{bucket_name}.storage.googleapis.com"'
' method="post" enctype="multipart/form-data">'
'<input type="text" name="key" value="my-test-key">'
'<input type="hidden" name="bucket" value="{bucket_name}">'
'<input type="hidden" name="acl" value="public-read">'
'<input name="file" type="file">'
'<input type="submit" value="Upload">'
"{policy_fields}"
"</form>"
).format(bucket_name=bucket.name, policy_fields=policy_fields)
print(upload_form)
# [END policy_document]
def _line_no(func):
code = getattr(func, "__code__", None) or getattr(func, "func_code")
return code.co_firstlineno
def _find_examples():
funcs = [obj for obj in globals().values() if getattr(obj, "_snippet", False)]
for func in sorted(funcs, key=_line_no):
yield func
def _name_and_doc(func):
return func.__name__, func.__doc__
def main():
client = storage.Client()
for example in _find_examples():
to_delete = []
print("%-25s: %s" % _name_and_doc(example))
try:
example(client, to_delete)
except AssertionError as failure:
print(" FAIL: %s" % (failure,))
except Exception as error: # pylint: disable=broad-except
print(" ERROR: %r" % (error,))
for item in to_delete:
item.delete()
if __name__ == "__main__":
main()