Skip to content

Commit 5ae4be8

Browse files
feat: add context manager support in client (#637)
- [ ] Regenerate this pull request now. PiperOrigin-RevId: 408420890 Source-Link: googleapis/googleapis@2921f9f Source-Link: googleapis/googleapis-gen@6598ca8 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjU5OGNhOGNiYmY1MjI2NzMzYTA5OWM0NTA2NTE4YTVhZjZmZjc0YyJ9 docs: list oneofs in docstring fix(deps): require google-api-core >= 1.28.0 fix(deps): drop packaging dependency feat: add context manager support in client chore: fix docstring for first attribute of protos fix: improper types in pagers generation chore: use gapic-generator-python 0.56.2
1 parent 5e0c364 commit 5ae4be8

File tree

35 files changed

+1195
-913
lines changed

35 files changed

+1195
-913
lines changed

google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py

Lines changed: 68 additions & 55 deletions
Large diffs are not rendered by default.

google/cloud/spanner_admin_database_v1/services/database_admin/client.py

Lines changed: 86 additions & 63 deletions
Large diffs are not rendered by default.

google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
#
1616
from typing import (
1717
Any,
18-
AsyncIterable,
18+
AsyncIterator,
1919
Awaitable,
2020
Callable,
21-
Iterable,
2221
Sequence,
2322
Tuple,
2423
Optional,
24+
Iterator,
2525
)
2626

2727
from google.cloud.spanner_admin_database_v1.types import backup
@@ -76,14 +76,14 @@ def __getattr__(self, name: str) -> Any:
7676
return getattr(self._response, name)
7777

7878
@property
79-
def pages(self) -> Iterable[spanner_database_admin.ListDatabasesResponse]:
79+
def pages(self) -> Iterator[spanner_database_admin.ListDatabasesResponse]:
8080
yield self._response
8181
while self._response.next_page_token:
8282
self._request.page_token = self._response.next_page_token
8383
self._response = self._method(self._request, metadata=self._metadata)
8484
yield self._response
8585

86-
def __iter__(self) -> Iterable[spanner_database_admin.Database]:
86+
def __iter__(self) -> Iterator[spanner_database_admin.Database]:
8787
for page in self.pages:
8888
yield from page.databases
8989

@@ -140,14 +140,14 @@ def __getattr__(self, name: str) -> Any:
140140
@property
141141
async def pages(
142142
self,
143-
) -> AsyncIterable[spanner_database_admin.ListDatabasesResponse]:
143+
) -> AsyncIterator[spanner_database_admin.ListDatabasesResponse]:
144144
yield self._response
145145
while self._response.next_page_token:
146146
self._request.page_token = self._response.next_page_token
147147
self._response = await self._method(self._request, metadata=self._metadata)
148148
yield self._response
149149

150-
def __aiter__(self) -> AsyncIterable[spanner_database_admin.Database]:
150+
def __aiter__(self) -> AsyncIterator[spanner_database_admin.Database]:
151151
async def async_generator():
152152
async for page in self.pages:
153153
for response in page.databases:
@@ -206,14 +206,14 @@ def __getattr__(self, name: str) -> Any:
206206
return getattr(self._response, name)
207207

208208
@property
209-
def pages(self) -> Iterable[backup.ListBackupsResponse]:
209+
def pages(self) -> Iterator[backup.ListBackupsResponse]:
210210
yield self._response
211211
while self._response.next_page_token:
212212
self._request.page_token = self._response.next_page_token
213213
self._response = self._method(self._request, metadata=self._metadata)
214214
yield self._response
215215

216-
def __iter__(self) -> Iterable[backup.Backup]:
216+
def __iter__(self) -> Iterator[backup.Backup]:
217217
for page in self.pages:
218218
yield from page.backups
219219

@@ -268,14 +268,14 @@ def __getattr__(self, name: str) -> Any:
268268
return getattr(self._response, name)
269269

270270
@property
271-
async def pages(self) -> AsyncIterable[backup.ListBackupsResponse]:
271+
async def pages(self) -> AsyncIterator[backup.ListBackupsResponse]:
272272
yield self._response
273273
while self._response.next_page_token:
274274
self._request.page_token = self._response.next_page_token
275275
self._response = await self._method(self._request, metadata=self._metadata)
276276
yield self._response
277277

278-
def __aiter__(self) -> AsyncIterable[backup.Backup]:
278+
def __aiter__(self) -> AsyncIterator[backup.Backup]:
279279
async def async_generator():
280280
async for page in self.pages:
281281
for response in page.backups:
@@ -334,14 +334,14 @@ def __getattr__(self, name: str) -> Any:
334334
return getattr(self._response, name)
335335

336336
@property
337-
def pages(self) -> Iterable[spanner_database_admin.ListDatabaseOperationsResponse]:
337+
def pages(self) -> Iterator[spanner_database_admin.ListDatabaseOperationsResponse]:
338338
yield self._response
339339
while self._response.next_page_token:
340340
self._request.page_token = self._response.next_page_token
341341
self._response = self._method(self._request, metadata=self._metadata)
342342
yield self._response
343343

344-
def __iter__(self) -> Iterable[operations_pb2.Operation]:
344+
def __iter__(self) -> Iterator[operations_pb2.Operation]:
345345
for page in self.pages:
346346
yield from page.operations
347347

@@ -400,14 +400,14 @@ def __getattr__(self, name: str) -> Any:
400400
@property
401401
async def pages(
402402
self,
403-
) -> AsyncIterable[spanner_database_admin.ListDatabaseOperationsResponse]:
403+
) -> AsyncIterator[spanner_database_admin.ListDatabaseOperationsResponse]:
404404
yield self._response
405405
while self._response.next_page_token:
406406
self._request.page_token = self._response.next_page_token
407407
self._response = await self._method(self._request, metadata=self._metadata)
408408
yield self._response
409409

410-
def __aiter__(self) -> AsyncIterable[operations_pb2.Operation]:
410+
def __aiter__(self) -> AsyncIterator[operations_pb2.Operation]:
411411
async def async_generator():
412412
async for page in self.pages:
413413
for response in page.operations:
@@ -466,14 +466,14 @@ def __getattr__(self, name: str) -> Any:
466466
return getattr(self._response, name)
467467

468468
@property
469-
def pages(self) -> Iterable[backup.ListBackupOperationsResponse]:
469+
def pages(self) -> Iterator[backup.ListBackupOperationsResponse]:
470470
yield self._response
471471
while self._response.next_page_token:
472472
self._request.page_token = self._response.next_page_token
473473
self._response = self._method(self._request, metadata=self._metadata)
474474
yield self._response
475475

476-
def __iter__(self) -> Iterable[operations_pb2.Operation]:
476+
def __iter__(self) -> Iterator[operations_pb2.Operation]:
477477
for page in self.pages:
478478
yield from page.operations
479479

@@ -528,14 +528,14 @@ def __getattr__(self, name: str) -> Any:
528528
return getattr(self._response, name)
529529

530530
@property
531-
async def pages(self) -> AsyncIterable[backup.ListBackupOperationsResponse]:
531+
async def pages(self) -> AsyncIterator[backup.ListBackupOperationsResponse]:
532532
yield self._response
533533
while self._response.next_page_token:
534534
self._request.page_token = self._response.next_page_token
535535
self._response = await self._method(self._request, metadata=self._metadata)
536536
yield self._response
537537

538-
def __aiter__(self) -> AsyncIterable[operations_pb2.Operation]:
538+
def __aiter__(self) -> AsyncIterator[operations_pb2.Operation]:
539539
async def async_generator():
540540
async for page in self.pages:
541541
for response in page.operations:

google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py

Lines changed: 17 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,14 @@
1515
#
1616
import abc
1717
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
18-
import packaging.version
1918
import pkg_resources
2019

2120
import google.auth # type: ignore
22-
import google.api_core # type: ignore
23-
from google.api_core import exceptions as core_exceptions # type: ignore
24-
from google.api_core import gapic_v1 # type: ignore
25-
from google.api_core import retry as retries # type: ignore
26-
from google.api_core import operations_v1 # type: ignore
21+
import google.api_core
22+
from google.api_core import exceptions as core_exceptions
23+
from google.api_core import gapic_v1
24+
from google.api_core import retry as retries
25+
from google.api_core import operations_v1
2726
from google.auth import credentials as ga_credentials # type: ignore
2827
from google.oauth2 import service_account # type: ignore
2928

@@ -44,15 +43,6 @@
4443
except pkg_resources.DistributionNotFound:
4544
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
4645

47-
try:
48-
# google.auth.__version__ was added in 1.26.0
49-
_GOOGLE_AUTH_VERSION = google.auth.__version__
50-
except AttributeError:
51-
try: # try pkg_resources if it is available
52-
_GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
53-
except pkg_resources.DistributionNotFound: # pragma: NO COVER
54-
_GOOGLE_AUTH_VERSION = None
55-
5646

5747
class DatabaseAdminTransport(abc.ABC):
5848
"""Abstract transport class for DatabaseAdmin."""
@@ -105,7 +95,7 @@ def __init__(
10595
host += ":443"
10696
self._host = host
10797

108-
scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
98+
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
10999

110100
# Save the scopes.
111101
self._scopes = scopes
@@ -127,7 +117,7 @@ def __init__(
127117
**scopes_kwargs, quota_project_id=quota_project_id
128118
)
129119

130-
# If the credentials is service account credentials, then always try to use self signed JWT.
120+
# If the credentials are service account credentials, then always try to use self signed JWT.
131121
if (
132122
always_use_jwt_access
133123
and isinstance(credentials, service_account.Credentials)
@@ -138,29 +128,6 @@ def __init__(
138128
# Save the credentials.
139129
self._credentials = credentials
140130

141-
# TODO(busunkim): This method is in the base transport
142-
# to avoid duplicating code across the transport classes. These functions
143-
# should be deleted once the minimum required versions of google-auth is increased.
144-
145-
# TODO: Remove this function once google-auth >= 1.25.0 is required
146-
@classmethod
147-
def _get_scopes_kwargs(
148-
cls, host: str, scopes: Optional[Sequence[str]]
149-
) -> Dict[str, Optional[Sequence[str]]]:
150-
"""Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
151-
152-
scopes_kwargs = {}
153-
154-
if _GOOGLE_AUTH_VERSION and (
155-
packaging.version.parse(_GOOGLE_AUTH_VERSION)
156-
>= packaging.version.parse("1.25.0")
157-
):
158-
scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
159-
else:
160-
scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
161-
162-
return scopes_kwargs
163-
164131
def _prep_wrapped_messages(self, client_info):
165132
# Precompute the wrapped methods.
166133
self._wrapped_methods = {
@@ -363,8 +330,17 @@ def _prep_wrapped_messages(self, client_info):
363330
),
364331
}
365332

333+
def close(self):
334+
"""Closes resources associated with the transport.
335+
336+
.. warning::
337+
Only call this method if the transport is NOT shared
338+
with other clients - this may cause errors in other clients!
339+
"""
340+
raise NotImplementedError()
341+
366342
@property
367-
def operations_client(self) -> operations_v1.OperationsClient:
343+
def operations_client(self):
368344
"""Return the client designed to process long-running operations."""
369345
raise NotImplementedError()
370346

google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
import warnings
1717
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
1818

19-
from google.api_core import grpc_helpers # type: ignore
20-
from google.api_core import operations_v1 # type: ignore
21-
from google.api_core import gapic_v1 # type: ignore
19+
from google.api_core import grpc_helpers
20+
from google.api_core import operations_v1
21+
from google.api_core import gapic_v1
2222
import google.auth # type: ignore
2323
from google.auth import credentials as ga_credentials # type: ignore
2424
from google.auth.transport.grpc import SslCredentials # type: ignore
@@ -92,16 +92,16 @@ def __init__(
9292
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
9393
If provided, it overrides the ``host`` argument and tries to create
9494
a mutual TLS channel with client SSL credentials from
95-
``client_cert_source`` or applicatin default SSL credentials.
95+
``client_cert_source`` or application default SSL credentials.
9696
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
9797
Deprecated. A callback to provide client SSL certificate bytes and
9898
private key bytes, both in PEM format. It is ignored if
9999
``api_mtls_endpoint`` is None.
100100
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
101-
for grpc channel. It is ignored if ``channel`` is provided.
101+
for the grpc channel. It is ignored if ``channel`` is provided.
102102
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
103103
A callback to provide client certificate bytes and private key bytes,
104-
both in PEM format. It is used to configure mutual TLS channel. It is
104+
both in PEM format. It is used to configure a mutual TLS channel. It is
105105
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
106106
quota_project_id (Optional[str]): An optional project to use for billing
107107
and quota.
@@ -122,7 +122,7 @@ def __init__(
122122
self._grpc_channel = None
123123
self._ssl_channel_credentials = ssl_channel_credentials
124124
self._stubs: Dict[str, Callable] = {}
125-
self._operations_client = None
125+
self._operations_client: Optional[operations_v1.OperationsClient] = None
126126

127127
if api_mtls_endpoint:
128128
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
@@ -815,5 +815,8 @@ def list_backup_operations(
815815
)
816816
return self._stubs["list_backup_operations"]
817817

818+
def close(self):
819+
self.grpc_channel.close()
820+
818821

819822
__all__ = ("DatabaseAdminGrpcTransport",)

google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,11 @@
1616
import warnings
1717
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
1818

19-
from google.api_core import gapic_v1 # type: ignore
20-
from google.api_core import grpc_helpers_async # type: ignore
21-
from google.api_core import operations_v1 # type: ignore
19+
from google.api_core import gapic_v1
20+
from google.api_core import grpc_helpers_async
21+
from google.api_core import operations_v1
2222
from google.auth import credentials as ga_credentials # type: ignore
2323
from google.auth.transport.grpc import SslCredentials # type: ignore
24-
import packaging.version
2524

2625
import grpc # type: ignore
2726
from grpc.experimental import aio # type: ignore
@@ -139,16 +138,16 @@ def __init__(
139138
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
140139
If provided, it overrides the ``host`` argument and tries to create
141140
a mutual TLS channel with client SSL credentials from
142-
``client_cert_source`` or applicatin default SSL credentials.
141+
``client_cert_source`` or application default SSL credentials.
143142
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
144143
Deprecated. A callback to provide client SSL certificate bytes and
145144
private key bytes, both in PEM format. It is ignored if
146145
``api_mtls_endpoint`` is None.
147146
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
148-
for grpc channel. It is ignored if ``channel`` is provided.
147+
for the grpc channel. It is ignored if ``channel`` is provided.
149148
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
150149
A callback to provide client certificate bytes and private key bytes,
151-
both in PEM format. It is used to configure mutual TLS channel. It is
150+
both in PEM format. It is used to configure a mutual TLS channel. It is
152151
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
153152
quota_project_id (Optional[str]): An optional project to use for billing
154153
and quota.
@@ -169,7 +168,7 @@ def __init__(
169168
self._grpc_channel = None
170169
self._ssl_channel_credentials = ssl_channel_credentials
171170
self._stubs: Dict[str, Callable] = {}
172-
self._operations_client = None
171+
self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
173172

174173
if api_mtls_endpoint:
175174
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
@@ -833,5 +832,8 @@ def list_backup_operations(
833832
)
834833
return self._stubs["list_backup_operations"]
835834

835+
def close(self):
836+
return self.grpc_channel.close()
837+
836838

837839
__all__ = ("DatabaseAdminGrpcAsyncIOTransport",)

google/cloud/spanner_admin_database_v1/types/backup.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242

4343
class Backup(proto.Message):
4444
r"""A backup of a Cloud Spanner database.
45+
4546
Attributes:
4647
database (str):
4748
Required for the
@@ -461,6 +462,7 @@ def raw_page(self):
461462

462463
class BackupInfo(proto.Message):
463464
r"""Information about a backup.
465+
464466
Attributes:
465467
backup (str):
466468
Name of the backup.
@@ -491,6 +493,7 @@ class BackupInfo(proto.Message):
491493

492494
class CreateBackupEncryptionConfig(proto.Message):
493495
r"""Encryption configuration for the backup to create.
496+
494497
Attributes:
495498
encryption_type (google.cloud.spanner_admin_database_v1.types.CreateBackupEncryptionConfig.EncryptionType):
496499
Required. The encryption type of the backup.

google/cloud/spanner_admin_database_v1/types/common.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ class OperationProgress(proto.Message):
4747

4848
class EncryptionConfig(proto.Message):
4949
r"""Encryption configuration for a Cloud Spanner database.
50+
5051
Attributes:
5152
kms_key_name (str):
5253
The Cloud KMS key to be used for encrypting and decrypting

0 commit comments

Comments
 (0)