Skip to content

Commit

Permalink
chore: allow sync init of AsyncConnector
Browse files Browse the repository at this point in the history
  • Loading branch information
jackwotherspoon committed Jan 12, 2024
1 parent 35d417d commit c8633ad
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
10 changes: 9 additions & 1 deletion google/cloud/alloydb/connector/async_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,13 @@ def __init__(
# otherwise use application default credentials
else:
self._credentials, _ = default(scopes=scopes)
self._keys = asyncio.create_task(generate_keys())

# check if AsyncConnector is being initialized with event loop running
# Otherwise we will lazy init keys
try:
self._keys = asyncio.create_task(generate_keys())
except RuntimeError:
self._keys = None
self._client: Optional[AlloyDBClient] = None

async def connect(
Expand All @@ -90,6 +96,8 @@ async def connect(
Returns:
connection: A DBAPI connection to the specified AlloyDB instance.
"""
if self._keys is None:
self._keys = asyncio.create_task(generate_keys)
if self._client is None:
# lazy init client as it has to be initialized in async context
self._client = AlloyDBClient(
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/test_async_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,8 @@ async def test_connect_unsupported_driver(
exc_info.value.args[0]
== "Driver 'bad_driver' is not a supported database driver."
)


def test_synchronous_init(credentials: FakeCredentials) -> None:
connector = AsyncConnector(credentials)
assert connector._keys is None

0 comments on commit c8633ad

Please sign in to comment.