Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4b55b54

Browse files
author
Takashi Matsuo
authored
docs: add a section about retry (GoogleCloudPlatform#3570)
* docs: add a section about retry * fix a link * really fix the link * correct format for the code sample
1 parent d296a96 commit 4b55b54

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

AUTHORING_GUIDE.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/
288288
* Use pytest's fixture for resource setup and teardown, instead of
289289
having them in the test itself.
290290
* Avoid infinite loops.
291+
* Retry RPCs
291292

292293
### Arrange, Act, Assert
293294

@@ -332,10 +333,15 @@ glossary_id = 'test-glossary-{}'.format(uuid.uuid4())
332333
or:
333334

334335
```python
335-
# If full uuid4 is too long, use hex representation.
336+
# If full uuid4 is too long, use its hex representation.
336337
encrypted_disk_name = 'test-disk-{}'.format(uuid.uuid4().hex)
337338
```
338339

340+
```python
341+
# If the hex representation is also too long, slice it.
342+
encrypted_disk_name = 'test-disk-{}'.format(uuid.uuid4().hex[:5]
343+
```
344+
339345
All temporary resources should be explicitly deleted when testing is
340346
complete. Use pytest's fixture for cleaning up these resouces instead
341347
of doing it in test itself.
@@ -384,6 +390,44 @@ This combination will give you very high success rate with fixed test
384390
execution time (0.999 success rate and 180 seconds operation wait time
385391
in the worst case in this example).
386392

393+
### Retry RPCs
394+
395+
All the RPCs are inevitably flaky. It can fail for many reasons. The
396+
`google-cloud` Python client retries requests automatically for most
397+
cases.
398+
399+
The old api-client doesn't retry automatically, so consider using
400+
[`backoff`](https://pypi.org/project/backoff/) for retrying. Here is a
401+
simple example:
402+
403+
```python
404+
405+
import backoff
406+
from googleapiclient.errors import HttpError
407+
408+
@pytest.fixture(scope='module')
409+
def test_resource():
410+
@backoff.on_exception(backoff.expo, HttpError, max_time=60)
411+
def create_resource():
412+
try:
413+
return client.projects().imaginaryResource().create(
414+
name=resource_id, body=body).execute()
415+
except HttpError as e:
416+
if '409' in str(e):
417+
# Ignore this case and get the existing one.
418+
return client.projects().imaginaryResource().get(
419+
name=resource_id).execute()
420+
else:
421+
raise
422+
423+
resource = create_resource()
424+
425+
yield resource
426+
427+
# cleanup
428+
...
429+
```
430+
387431
### Running tests
388432

389433
Automated testing for samples in `python-docs-samples` is managed by

0 commit comments

Comments
 (0)