Skip to content

GbqConnector should be able to fetch default credentials on Google Compute Engine #13608

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ Using the anchoring suffix, you can also specify the day of month to use instead
Other enhancements
^^^^^^^^^^^^^^^^^^

- The ``.get_credentials()`` method of ``GbqConnector`` can now first try to fetch the default credentials for Google Compute Engine without the need to run ``OAuth2WebServerFlow`` - if private_key is not provided (:issue:`13577`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a bit confusing to a reader. pls make several sentences.


- The ``.tz_localize()`` method of ``DatetimeIndex`` and ``Timestamp`` has gained the ``errors`` keyword, so you can potentially coerce nonexistent timestamps to ``NaT``. The default behaviour remains to raising a ``NonExistentTimeError`` (:issue:`13057`)

- ``Index`` now supports ``.str.extractall()`` which returns a ``DataFrame``, see :ref:`documentation here <text.extractall>` (:issue:`10008`, :issue:`13156`)
Expand Down
50 changes: 47 additions & 3 deletions pandas/io/gbq.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,47 @@ def get_credentials(self):
if self.private_key:
return self.get_service_account_credentials()
else:
return self.get_user_account_credentials()
# Try to retrieve Application Default Credentials
project_id = self.project_id
credentials = self.get_application_default_credentials(project_id)
if not credentials:
credentials = self.get_user_account_credentials()
return credentials

@staticmethod
def get_application_default_credentials(project_id): # pragma: no cover
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you need to follow the existing pattern, why is this a staticmethod? that's non-pythonic.

nested try/except is a no-no

just call your routine, if the default oauth imports raise you don't care, the user will get an import error.

only the addl imports (for getting default credientials) need to be caught (and return None).
you can

"""
Given a project_id tries to retrieve the
"default application credentials"
Could be useful for running code on Google Cloud Platform
"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a Returns section. Explaining that it will return the credentials or None if not found / error.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

explain the conditions under which this will get the correct credentials

credentials = None
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are these libararies a newer / different version that we are currently importing?

from oauth2client.client import GoogleCredentials
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can just put all of the imports in 1 try/except block

from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import ApplicationDefaultCredentialsError
try:
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
except:
from apiclient.discovery import build
from apiclient.errors import HttpError
except ImportError:
return None

try:
credentials = GoogleCredentials.get_application_default()
except ApplicationDefaultCredentialsError:
return None
# Check if the application has rights to the BigQuery project
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blank line

bigquery_service = build('bigquery', 'v2', credentials=credentials)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs to be in try for compatibility with google-api-python-client==1.2

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@parthea I've changed the call to the "build" method - should work for both api versions now.

jobs = bigquery_service.jobs()
job_data = {'configuration': {'query': {'query': 'SELECT 1'}}}
try:
jobs.insert(projectId=project_id, body=job_data).execute()
except (AccessTokenRefreshError, HttpError, TypeError):
return None
return credentials

def get_user_account_credentials(self):
from oauth2client.client import OAuth2WebServerFlow
Expand Down Expand Up @@ -576,7 +616,9 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None,
https://developers.google.com/api-client-library/python/apis/bigquery/v2

Authentication to the Google BigQuery service is via OAuth 2.0.
By default user account credentials are used. You will be asked to
By default "application default credentials" are used.
If default application credentials are not found or are restrictive -
User account credentials are used. You will be asked to
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need an indication that this is new behavior

grant permissions for product name 'pandas GBQ'. It is also posible
to authenticate via service account credentials by using
private_key parameter.
Expand Down Expand Up @@ -672,7 +714,9 @@ def to_gbq(dataframe, destination_table, project_id, chunksize=10000,
https://developers.google.com/api-client-library/python/apis/bigquery/v2

Authentication to the Google BigQuery service is via OAuth 2.0.
By default user account credentials are used. You will be asked to
By default "application default credentials" are used.
If default application credentials are not found or are restrictive -
User account credentials are used. You will be asked to
grant permissions for product name 'pandas GBQ'. It is also posible
to authenticate via service account credentials by using
private_key parameter.
Expand Down
17 changes: 17 additions & 0 deletions pandas/io/tests/test_gbq.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def _test_imports():
from apiclient.discovery import build # noqa
from apiclient.errors import HttpError # noqa

from oauth2client.client import GoogleCredentials # noqa
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this inside of try so tests pass with oauth2client==1.2

from oauth2client.client import OAuth2WebServerFlow # noqa
from oauth2client.client import AccessTokenRefreshError # noqa

Expand Down Expand Up @@ -188,6 +189,22 @@ def test_generate_bq_schema_deprecated():
gbq.generate_bq_schema(df)


def google_credentials_import():
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

include this in the standard import tests

from oauth2client.client import GoogleCredentials
return GoogleCredentials
except ImportError:
return type(None)


def test_should_be_able_to_get_credentials_from_default_credentials():
GoogleCredentials = google_credentials_import()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls follow the existing patterns

connector = gbq.GbqConnector
credentials = connector.get_application_default_credentials(PROJECT_ID)
valid_types = (type(None), GoogleCredentials)
assert isinstance(credentials, valid_types)


class TestGBQConnectorIntegration(tm.TestCase):

def setUp(self):
Expand Down