From fc5a4d69b5eb98c627ea78a4c04d349ac7e61463 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Wed, 23 Sep 2020 20:16:06 -0700 Subject: [PATCH 01/14] docs: added a sample --- samples/snippets/quickstart.py | 101 ++++++++++++++++++++++++++++ samples/snippets/quickstart_test.py | 22 ++++++ 2 files changed, 123 insertions(+) create mode 100644 samples/snippets/quickstart.py create mode 100644 samples/snippets/quickstart_test.py diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py new file mode 100644 index 0000000..1525dd2 --- /dev/null +++ b/samples/snippets/quickstart.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python + +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Data API sample quickstart application. +Example usage: + python quickstart.py --property_id + + where is the Google Analytics property id to use for a query. + +Note: you need to have the Google Analytics Data API enabled in your project +prior to running this sample. Please visit the following URL and make sure the +API is enabled: + +https://console.developers.google.com/apis/library/analyticsdata.googleapis.com + +This application demonstrates the usage of the Analytics Data API using +service account credentials. For more information on service accounts, see + +https://cloud.google.com/iam/docs/understanding-service-accounts + +The following document provides instructions on setting service account +credentials for your application: + + https://cloud.google.com/docs/authentication/production + +In a nutshell, you need to: +1. Create a service account and download the key JSON file. + +https://cloud.google.com/docs/authentication/production#creating_a_service_account + +2. Provide service account credentials using one of the following options: +- set the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API +client will use the value of this variable to find the service account key +JSON file. + +https://cloud.google.com/docs/authentication/production#setting_the_environment_variable + +OR +- manually pass the path to the service account key JSON file to the API client +by specifying the keyFilename parameter in the constructor: +https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code + +To install the latest published package dependency, execute the following: + pip install google-analytics-data +""" +import argparse + +# [START ga_data_run_report] +from google.analytics.data import AlphaAnalyticsDataClient +from google.analytics.data_v1alpha.types import DateRange +from google.analytics.data_v1alpha.types import Dimension +from google.analytics.data_v1alpha.types import Entity +from google.analytics.data_v1alpha.types import Metric +from google.analytics.data_v1alpha.types import RunReportRequest + + +def sample_run_report(property_id): + """Runs a simple report on a Google Analytics App+Web property.""" + + # Using a default constructor instructs the client to use the credentials + # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. + client = AlphaAnalyticsDataClient() + request = RunReportRequest(entity=Entity(property_id=property_id), + dimensions=[Dimension(name='city')], + metrics=[Metric(name='activeUsers')], + date_ranges=[DateRange(start_date='2020-03-31', + end_date='today')]) + response = client.run_report(request) + + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) + + +# [END ga_data_run_report] + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "--property_id", + type=str, + required=True, + help="Google Analytics property ID to use for a query.", + ) + args = parser.parse_args() + sample_run_report(args.property_id) diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py new file mode 100644 index 0000000..7e1d307 --- /dev/null +++ b/samples/snippets/quickstart_test.py @@ -0,0 +1,22 @@ +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +import quickstart + + +def test_quickstart(capsys): + TEST_PROPERTY_ID = '222596558' + quickstart.sample_run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out From 0a74ac1e56d772a1ef1cfb02201873c784700ff4 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Thu, 5 Nov 2020 11:47:52 -0800 Subject: [PATCH 02/14] docs: usage instructions updated to use Python3 --- samples/snippets/quickstart.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 1525dd2..b667caf 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -16,7 +16,7 @@ """Google Analytics Data API sample quickstart application. Example usage: - python quickstart.py --property_id + python3 quickstart.py --property_id where is the Google Analytics property id to use for a query. @@ -54,7 +54,7 @@ https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code To install the latest published package dependency, execute the following: - pip install google-analytics-data + pip3 install google-analytics-data """ import argparse From 4156c3271cb6a5b9cf833fce42eab88fd0cd21c5 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 5 Jan 2021 12:34:23 -0800 Subject: [PATCH 03/14] docs: updated sample to include main() method --- samples/snippets/quickstart.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index b667caf..246cac2 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2020 Google Inc. All Rights Reserved. +# Copyright 2021 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -56,8 +56,6 @@ To install the latest published package dependency, execute the following: pip3 install google-analytics-data """ -import argparse - # [START ga_data_run_report] from google.analytics.data import AlphaAnalyticsDataClient from google.analytics.data_v1alpha.types import DateRange @@ -88,6 +86,8 @@ def sample_run_report(property_id): # [END ga_data_run_report] if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, ) @@ -95,7 +95,11 @@ def sample_run_report(property_id): "--property_id", type=str, required=True, - help="Google Analytics property ID to use for a query.", + help="Google Analytics 4 property ID to use for a query.", ) args = parser.parse_args() sample_run_report(args.property_id) + +if __name__ == "__main__": + main() + From b59f40d73db95683988658f90636b1985ffa246e Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Thu, 25 Feb 2021 18:31:01 -0800 Subject: [PATCH 04/14] docs: update the sample to support the Google Analytics Data API v1 beta --- samples/snippets/quickstart.py | 120 +++++++++++--------------- samples/snippets/quickstart_oauth2.py | 80 +++++++++++++++++ 2 files changed, 130 insertions(+), 70 deletions(-) create mode 100644 samples/snippets/quickstart_oauth2.py diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index e2bb3bf..1250075 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -15,89 +15,69 @@ # limitations under the License. """Google Analytics Data API sample quickstart application. -Example usage: - python3 quickstart.py --property_id - - where is the Google Analytics property id to use for a query. - -Note: you need to have the Google Analytics Data API enabled in your project -prior to running this sample. Please visit the following URL and make sure the -API is enabled: - -https://console.developers.google.com/apis/library/analyticsdata.googleapis.com This application demonstrates the usage of the Analytics Data API using -service account credentials. For more information on service accounts, see - -https://cloud.google.com/iam/docs/understanding-service-accounts - -The following document provides instructions on setting service account -credentials for your application: - - https://cloud.google.com/docs/authentication/production - -In a nutshell, you need to: -1. Create a service account and download the key JSON file. - -https://cloud.google.com/docs/authentication/production#creating_a_service_account - -2. Provide service account credentials using one of the following options: -- set the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API -client will use the value of this variable to find the service account key -JSON file. - -https://cloud.google.com/docs/authentication/production#setting_the_environment_variable - -OR -- manually pass the path to the service account key JSON file to the API client -by specifying the keyFilename parameter in the constructor: -https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code - -To install the latest published package dependency, execute the following: - pip3 install google-analytics-data -# [START ga_data_run_report] -from google.analytics.data import AlphaAnalyticsDataClient -from google.analytics.data_v1alpha.types import DateRange -from google.analytics.data_v1alpha.types import Dimension -from google.analytics.data_v1alpha.types import Entity -from google.analytics.data_v1alpha.types import Metric -from google.analytics.data_v1alpha.types import RunReportRequest - - -def sample_run_report(property_id): - """Runs a simple report on a Google Analytics App+Web property.""" - - # Using a default constructor instructs the client to use the credentials - # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. - client = AlphaAnalyticsDataClient() - request = RunReportRequest(entity=Entity(property_id=property_id), +service account credentials. + +Before you start the application, please review the comments starting with +"TODO(developer)" and update the code to use correct values. + +Usage: + pip3 install --upgrade google-analytics-data + python3 quickstart.py +""" +# [START google_analytics_data_quickstart] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunReportRequest + + +def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + #property_id = 'YOUR-GA4-PROPERTY-ID' + + # [START google_analytics_data_initialize] + + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + # Otherwise, default service account credentials will be derived from + # the GOOGLE_APPLICATION_CREDENTIALS environment variable. + #credentials_json_path = '/path/to/credentials.json' + + if credentials_json_path: + # Explicitly use service account credentials by specifying + # the private key file. + client = BetaAnalyticsDataClient().from_service_account_json( + credentials_json_path) + else: + # Using a default constructor instructs the client to use the credentials + # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. + client = BetaAnalyticsDataClient() + + # [END google_analytics_data_initialize] + + # [START google_analytics_data_run_report] + request = RunReportRequest(property='properties/' + str(property_id), dimensions=[Dimension(name='city')], metrics=[Metric(name='activeUsers')], date_ranges=[DateRange(start_date='2020-03-31', end_date='today')]) response = client.run_report(request) + # [END google_analytics_data_run_report] print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) +# [END google_analytics_data_quickstart] -# [END ga_data_run_report] - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, - ) - parser.add_argument( - "--property_id", - type=str, - required=True, - help="Google Analytics 4 property ID to use for a query.", - ) - args = parser.parse_args() - sample_run_report(args.property_id) +def main(): + sample_run_report() if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py new file mode 100644 index 0000000..9a2100a --- /dev/null +++ b/samples/snippets/quickstart_oauth2.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Data API sample quickstart application. + +This application demonstrates the usage of the Analytics Data API using +OAuth2 credentials. + +Before you start the application, please review the comments starting with +"TODO(developer)" and update the code to use correct values. + +Usage: + pip3 install --upgrade google-analytics-data + python3 quickstart.py +""" +# [START ga_data_run_report] +from google_auth_oauthlib import flow + +from google.analytics.data import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunReportRequest + + +def sample_run_report(credentials): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + #property_id = 'YOUR-GA4-PROPERTY-ID' + + client = BetaAnalyticsDataClient(credentials=credentials) + request = RunReportRequest(property='properties/' + str(property_id), + dimensions=[Dimension(name='city')], + metrics=[Metric(name='activeUsers')], + date_ranges=[DateRange(start_date='2020-03-31', + end_date='today')]) + + response = client.run_report(request) + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) +# [END ga_data_run_report] + +def main(): + appflow = flow.InstalledAppFlow.from_client_secrets_file( + "client_secrets.json", + scopes=["https://www.googleapis.com/auth/analytics.readonly"] + ) + # TODO: Uncomment the line below to set the `launch_browser` variable. + launch_browser = True + # The `launch_browser` boolean variable indicates if a local server is used + # as the callback URL in the auth flow. A value of `True` is recommended, + # but a local server does not work if accessing the application remotely, + # such as over SSH or from a remote Jupyter notebook. + + if launch_browser: + appflow.run_local_server() + else: + appflow.run_console() + + credentials = appflow.credentials + sample_run_report(credentials) + + +if __name__ == "__main__": + main() From fc29aa099e3668a133fa8023d924fc28bbfada1c Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 02:33:00 -0700 Subject: [PATCH 05/14] docs: update quickstart samples to support the Data API v1 beta --- samples/snippets/quickstart.py | 26 ++----- .../snippets/quickstart_json_credentials.py | 75 +++++++++++++++++++ .../quickstart_json_credentials_test.py | 22 ++++++ samples/snippets/quickstart_oauth2.py | 6 +- samples/snippets/quickstart_oauth2_test.py | 22 ++++++ 5 files changed, 128 insertions(+), 23 deletions(-) create mode 100644 samples/snippets/quickstart_json_credentials.py create mode 100644 samples/snippets/quickstart_json_credentials_test.py create mode 100644 samples/snippets/quickstart_oauth2_test.py diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 1250075..1d48a9e 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -34,31 +34,16 @@ from google.analytics.data_v1beta.types import RunReportRequest -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): +def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. #property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_initialize] - - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - # Otherwise, default service account credentials will be derived from - # the GOOGLE_APPLICATION_CREDENTIALS environment variable. - #credentials_json_path = '/path/to/credentials.json' - - if credentials_json_path: - # Explicitly use service account credentials by specifying - # the private key file. - client = BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - else: - # Using a default constructor instructs the client to use the credentials - # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. - client = BetaAnalyticsDataClient() - + # Using a default constructor instructs the client to use the credentials + # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. + client = BetaAnalyticsDataClient() # [END google_analytics_data_initialize] # [START google_analytics_data_run_report] @@ -70,10 +55,11 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path= response = client.run_report(request) # [END google_analytics_data_run_report] + # [START google_analytics_data_run_report_response] print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) - + # [END google_analytics_data_run_report_response] # [END google_analytics_data_quickstart] def main(): diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py new file mode 100644 index 0000000..72da246 --- /dev/null +++ b/samples/snippets/quickstart_json_credentials.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Data API sample quickstart application. + +This application demonstrates the usage of the Analytics Data API using +service account credentials. + +Before you start the application, please review the comments starting with +"TODO(developer)" and update the code to use correct values. + +Usage: + pip3 install --upgrade google-analytics-data + python3 quickstart.py +""" +# [START google_analytics_data_quickstart] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunReportRequest + + +def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + #property_id = 'YOUR-GA4-PROPERTY-ID' + + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + # Otherwise, default service account credentials will be derived from + # the GOOGLE_APPLICATION_CREDENTIALS environment variable. + #credentials_json_path = '/path/to/credentials.json' + + # Explicitly use service account credentials by specifying + # the private key file. + client = BetaAnalyticsDataClient().from_service_account_json( + credentials_json_path) + # [END google_analytics_data_initialize] + + # [START google_analytics_data_run_report] + request = RunReportRequest(property='properties/' + str(property_id), + dimensions=[Dimension(name='city')], + metrics=[Metric(name='activeUsers')], + date_ranges=[DateRange(start_date='2020-03-31', + end_date='today')]) + response = client.run_report(request) + # [END google_analytics_data_run_report] + + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) +# [END google_analytics_data_quickstart] + +def main(): + sample_run_report() + +if __name__ == "__main__": + main() diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py new file mode 100644 index 0000000..a0af1d6 --- /dev/null +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -0,0 +1,22 @@ +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +import quickstart_json_credentials + + +def test_quickstart(capsys): + TEST_PROPERTY_ID = '222596558' + quickstart_json_credentials.sample_run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 9a2100a..2feef75 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -24,9 +24,9 @@ Usage: pip3 install --upgrade google-analytics-data - python3 quickstart.py + python3 quickstart_oauth2.py """ -# [START ga_data_run_report] +# [START google_analytics_data_quickstart] from google_auth_oauthlib import flow from google.analytics.data import BetaAnalyticsDataClient @@ -53,7 +53,6 @@ def sample_run_report(credentials): print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) -# [END ga_data_run_report] def main(): appflow = flow.InstalledAppFlow.from_client_secrets_file( @@ -75,6 +74,7 @@ def main(): credentials = appflow.credentials sample_run_report(credentials) +# [END google_analytics_data_quickstart] if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py new file mode 100644 index 0000000..709e440 --- /dev/null +++ b/samples/snippets/quickstart_oauth2_test.py @@ -0,0 +1,22 @@ +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +import quickstart_oauth2 + + +def test_quickstart(capsys): + TEST_PROPERTY_ID = '222596558' + quickstart_oauth2.sample_run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out From df8b945b046c2571d4484c4fd7d4ad8cd5fa39e0 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 02:33:00 -0700 Subject: [PATCH 06/14] docs: update quickstart samples to support the Data API v1 beta --- samples/snippets/quickstart.py | 26 ++----- .../snippets/quickstart_json_credentials.py | 75 +++++++++++++++++++ .../quickstart_json_credentials_test.py | 22 ++++++ samples/snippets/quickstart_oauth2.py | 15 ++-- samples/snippets/quickstart_oauth2_test.py | 22 ++++++ 5 files changed, 133 insertions(+), 27 deletions(-) create mode 100644 samples/snippets/quickstart_json_credentials.py create mode 100644 samples/snippets/quickstart_json_credentials_test.py create mode 100644 samples/snippets/quickstart_oauth2_test.py diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 1250075..1d48a9e 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -34,31 +34,16 @@ from google.analytics.data_v1beta.types import RunReportRequest -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): +def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. #property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_initialize] - - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - # Otherwise, default service account credentials will be derived from - # the GOOGLE_APPLICATION_CREDENTIALS environment variable. - #credentials_json_path = '/path/to/credentials.json' - - if credentials_json_path: - # Explicitly use service account credentials by specifying - # the private key file. - client = BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - else: - # Using a default constructor instructs the client to use the credentials - # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. - client = BetaAnalyticsDataClient() - + # Using a default constructor instructs the client to use the credentials + # specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. + client = BetaAnalyticsDataClient() # [END google_analytics_data_initialize] # [START google_analytics_data_run_report] @@ -70,10 +55,11 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path= response = client.run_report(request) # [END google_analytics_data_run_report] + # [START google_analytics_data_run_report_response] print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) - + # [END google_analytics_data_run_report_response] # [END google_analytics_data_quickstart] def main(): diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py new file mode 100644 index 0000000..7055770 --- /dev/null +++ b/samples/snippets/quickstart_json_credentials.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Data API sample quickstart application. + +This application demonstrates the usage of the Analytics Data API using +service account credentials. + +Before you start the application, please review the comments starting with +"TODO(developer)" and update the code to use correct values. + +Usage: + pip3 install --upgrade google-analytics-data + python3 quickstart_json_credentials.py +""" +# [START google_analytics_data_quickstart] +from google.analytics.data_v1beta import BetaAnalyticsDataClient +from google.analytics.data_v1beta.types import DateRange +from google.analytics.data_v1beta.types import Dimension +from google.analytics.data_v1beta.types import Metric +from google.analytics.data_v1beta.types import RunReportRequest + + +def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + #property_id = 'YOUR-GA4-PROPERTY-ID' + + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + # Otherwise, default service account credentials will be derived from + # the GOOGLE_APPLICATION_CREDENTIALS environment variable. + #credentials_json_path = '/path/to/credentials.json' + + # Explicitly use service account credentials by specifying + # the private key file. + client = BetaAnalyticsDataClient().from_service_account_json( + credentials_json_path) + # [END google_analytics_data_initialize] + + # [START google_analytics_data_run_report] + request = RunReportRequest(property='properties/' + str(property_id), + dimensions=[Dimension(name='city')], + metrics=[Metric(name='activeUsers')], + date_ranges=[DateRange(start_date='2020-03-31', + end_date='today')]) + response = client.run_report(request) + # [END google_analytics_data_run_report] + + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) +# [END google_analytics_data_quickstart] + +def main(): + sample_run_report() + +if __name__ == "__main__": + main() diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py new file mode 100644 index 0000000..a0af1d6 --- /dev/null +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -0,0 +1,22 @@ +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +import quickstart_json_credentials + + +def test_quickstart(capsys): + TEST_PROPERTY_ID = '222596558' + quickstart_json_credentials.sample_run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 9a2100a..2eed568 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -24,9 +24,9 @@ Usage: pip3 install --upgrade google-analytics-data - python3 quickstart.py + python3 quickstart_oauth2.py """ -# [START ga_data_run_report] +# [START google_analytics_data_quickstart] from google_auth_oauthlib import flow from google.analytics.data import BetaAnalyticsDataClient @@ -50,23 +50,23 @@ def sample_run_report(credentials): end_date='today')]) response = client.run_report(request) + print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) -# [END ga_data_run_report] def main(): + # [START google_analytics_data_initialize] appflow = flow.InstalledAppFlow.from_client_secrets_file( "client_secrets.json", scopes=["https://www.googleapis.com/auth/analytics.readonly"] ) - # TODO: Uncomment the line below to set the `launch_browser` variable. - launch_browser = True + # TODO(developer): Update the line below to set the `launch_browser` variable. # The `launch_browser` boolean variable indicates if a local server is used # as the callback URL in the auth flow. A value of `True` is recommended, # but a local server does not work if accessing the application remotely, # such as over SSH or from a remote Jupyter notebook. - + launch_browser = True if launch_browser: appflow.run_local_server() else: @@ -74,7 +74,8 @@ def main(): credentials = appflow.credentials sample_run_report(credentials) - + # [END google_analytics_data_initialize] +# [END google_analytics_data_quickstart] if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py new file mode 100644 index 0000000..709e440 --- /dev/null +++ b/samples/snippets/quickstart_oauth2_test.py @@ -0,0 +1,22 @@ +# Copyright 2020 Google Inc. All Rights Reserved. +# +# 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. + +import quickstart_oauth2 + + +def test_quickstart(capsys): + TEST_PROPERTY_ID = '222596558' + quickstart_oauth2.sample_run_report(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out From 050994a9cd93fbbd758b064d552b04d70b0288ed Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 13:56:11 -0700 Subject: [PATCH 07/14] separate the sample into separate methods to facilitate testing --- .../snippets/quickstart_json_credentials.py | 34 +++++++++---------- .../quickstart_json_credentials_test.py | 10 +++--- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 548908d..7181388 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -34,27 +34,26 @@ from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest +def get_client(credentials_json_path=''): + """Creates an API client instance.""" + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + #credentials_json_path = '/path/to/credentials.json' -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): + # Explicitly use service account credentials by specifying + # the private key file. + return BetaAnalyticsDataClient().from_service_account_json( + credentials_json_path) + # [END google_analytics_data_initialize] + +def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. #property_id = 'YOUR-GA4-PROPERTY-ID' - # [START google_analytics_data_initialize] - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - # Otherwise, default service account credentials will be derived from - # the GOOGLE_APPLICATION_CREDENTIALS environment variable. - #credentials_json_path = '/path/to/credentials.json' - - # Explicitly use service account credentials by specifying - # the private key file. - client = BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - # [END google_analytics_data_initialize] - # [START google_analytics_data_run_report] request = RunReportRequest(property='properties/' + str(property_id), dimensions=[Dimension(name='city')], @@ -67,10 +66,11 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path= print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) -# [END google_analytics_data_quickstart] def main(): - sample_run_report() + client = get_client() + sample_run_report(client) +# [END google_analytics_data_quickstart] if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index a0af1d6..7181246 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -12,11 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +from google.analytics.data_v1beta import BetaAnalyticsDataClient import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' - quickstart_json_credentials.sample_run_report(TEST_PROPERTY_ID) - out, _ = capsys.readouterr() - assert "Report result" in out + TEST_PROPERTY_ID = '222596558' + quickstart_json_credentials.sample_run_report(BetaAnalyticsDataClient(), + TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out From c13340ff48e64ad3a70f1eb7cf146277c236b2f2 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 13:56:11 -0700 Subject: [PATCH 08/14] separate the sample into separate methods to facilitate testing --- .../snippets/quickstart_json_credentials.py | 34 +++++++++---------- .../quickstart_json_credentials_test.py | 10 +++--- samples/snippets/quickstart_oauth2.py | 9 +++-- 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 548908d..7181388 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -34,27 +34,26 @@ from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest +def get_client(credentials_json_path=''): + """Creates an API client instance.""" + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + #credentials_json_path = '/path/to/credentials.json' -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path=''): + # Explicitly use service account credentials by specifying + # the private key file. + return BetaAnalyticsDataClient().from_service_account_json( + credentials_json_path) + # [END google_analytics_data_initialize] + +def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. #property_id = 'YOUR-GA4-PROPERTY-ID' - # [START google_analytics_data_initialize] - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - # Otherwise, default service account credentials will be derived from - # the GOOGLE_APPLICATION_CREDENTIALS environment variable. - #credentials_json_path = '/path/to/credentials.json' - - # Explicitly use service account credentials by specifying - # the private key file. - client = BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - # [END google_analytics_data_initialize] - # [START google_analytics_data_run_report] request = RunReportRequest(property='properties/' + str(property_id), dimensions=[Dimension(name='city')], @@ -67,10 +66,11 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID', credentials_json_path= print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) -# [END google_analytics_data_quickstart] def main(): - sample_run_report() + client = get_client() + sample_run_report(client) +# [END google_analytics_data_quickstart] if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index a0af1d6..7181246 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -12,11 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +from google.analytics.data_v1beta import BetaAnalyticsDataClient import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' - quickstart_json_credentials.sample_run_report(TEST_PROPERTY_ID) - out, _ = capsys.readouterr() - assert "Report result" in out + TEST_PROPERTY_ID = '222596558' + quickstart_json_credentials.sample_run_report(BetaAnalyticsDataClient(), + TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 9220e0f..40ab5de 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -56,7 +56,8 @@ def sample_run_report(credentials=None, property_id='YOUR-GA4-PROPERTY-ID'): for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) -def main(): +def get_credentials(): + """Creates an OAuth2 credentials instance.""" # [START google_analytics_data_initialize] appflow = flow.InstalledAppFlow.from_client_secrets_file( "client_secrets.json", @@ -72,10 +73,12 @@ def main(): appflow.run_local_server() else: appflow.run_console() + return appflow.credentials + # [END google_analytics_data_initialize] - credentials = appflow.credentials +def main(): + credentials = get_credentials() sample_run_report(credentials) - # [END google_analytics_data_initialize] # [END google_analytics_data_quickstart] if __name__ == "__main__": From 49a7ac7ecd2b426619a4428a1574da785f2ad826 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 23:39:14 -0700 Subject: [PATCH 09/14] fix: update formatting --- samples/snippets/quickstart.py | 19 +++-- .../snippets/quickstart_json_credentials.py | 47 ++++++----- .../quickstart_json_credentials_test.py | 12 +-- samples/snippets/quickstart_oauth2.py | 80 ++++++++++--------- samples/snippets/quickstart_oauth2_test.py | 2 +- samples/snippets/quickstart_test.py | 2 +- 6 files changed, 89 insertions(+), 73 deletions(-) diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 1d48a9e..b13dcd2 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -34,11 +34,11 @@ from google.analytics.data_v1beta.types import RunReportRequest -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): +def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_initialize] # Using a default constructor instructs the client to use the credentials @@ -47,11 +47,12 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): # [END google_analytics_data_initialize] # [START google_analytics_data_run_report] - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) response = client.run_report(request) # [END google_analytics_data_run_report] @@ -60,10 +61,14 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) # [END google_analytics_data_run_report_response] + + # [END google_analytics_data_quickstart] + def main(): sample_run_report() + if __name__ == "__main__": main() diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 7181388..87f2a4d 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -34,32 +34,34 @@ from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest -def get_client(credentials_json_path=''): - """Creates an API client instance.""" - # [START google_analytics_data_initialize] - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - #credentials_json_path = '/path/to/credentials.json' - - # Explicitly use service account credentials by specifying - # the private key file. - return BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - # [END google_analytics_data_initialize] - -def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): + +def get_client(credentials_json_path=""): + """Creates an API client instance.""" + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + # credentials_json_path = '/path/to/credentials.json' + + # Explicitly use service account credentials by specifying + # the private key file. + return BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) + # [END google_analytics_data_initialize] + + +def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_run_report] - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) response = client.run_report(request) # [END google_analytics_data_run_report] @@ -67,9 +69,12 @@ def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) + def main(): client = get_client() sample_run_report(client) + + # [END google_analytics_data_quickstart] if __name__ == "__main__": diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index 7181246..675106a 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -13,12 +13,14 @@ # limitations under the License. from google.analytics.data_v1beta import BetaAnalyticsDataClient + import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' - quickstart_json_credentials.sample_run_report(BetaAnalyticsDataClient(), - TEST_PROPERTY_ID) - out, _ = capsys.readouterr() - assert "Report result" in out + TEST_PROPERTY_ID = "222596558" + quickstart_json_credentials.sample_run_report( + BetaAnalyticsDataClient(), TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 40ab5de..3cef039 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -28,58 +28,62 @@ python3 quickstart_oauth2.py """ # [START google_analytics_data_quickstart] -from google_auth_oauthlib import flow - from google.analytics.data import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange from google.analytics.data_v1beta.types import Dimension from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest +from google_auth_oauthlib import flow + +def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + # property_id = 'YOUR-GA4-PROPERTY-ID' -def sample_run_report(credentials=None, property_id='YOUR-GA4-PROPERTY-ID'): - """Runs a simple report on a Google Analytics 4 property.""" - # TODO(developer): Uncomment this variable and replace with your - # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + client = BetaAnalyticsDataClient(credentials=credentials) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) - client = BetaAnalyticsDataClient(credentials=credentials) - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + response = client.run_report(request) - response = client.run_report(request) + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) - print("Report result:") - for row in response.rows: - print(row.dimension_values[0].value, row.metric_values[0].value) def get_credentials(): - """Creates an OAuth2 credentials instance.""" - # [START google_analytics_data_initialize] - appflow = flow.InstalledAppFlow.from_client_secrets_file( - "client_secrets.json", - scopes=["https://www.googleapis.com/auth/analytics.readonly"] - ) - # TODO(developer): Update the line below to set the `launch_browser` variable. - # The `launch_browser` boolean variable indicates if a local server is used - # as the callback URL in the auth flow. A value of `True` is recommended, - # but a local server does not work if accessing the application remotely, - # such as over SSH or from a remote Jupyter notebook. - launch_browser = True - if launch_browser: - appflow.run_local_server() - else: - appflow.run_console() - return appflow.credentials - # [END google_analytics_data_initialize] + """Creates an OAuth2 credentials instance.""" + # [START google_analytics_data_initialize] + appflow = flow.InstalledAppFlow.from_client_secrets_file( + "client_secrets.json", + scopes=["https://www.googleapis.com/auth/analytics.readonly"], + ) + # TODO(developer): Update the line below to set the `launch_browser` variable. + # The `launch_browser` boolean variable indicates if a local server is used + # as the callback URL in the auth flow. A value of `True` is recommended, + # but a local server does not work if accessing the application remotely, + # such as over SSH or from a remote Jupyter notebook. + launch_browser = True + if launch_browser: + appflow.run_local_server() + else: + appflow.run_console() + return appflow.credentials + # [END google_analytics_data_initialize] + def main(): - credentials = get_credentials() - sample_run_report(credentials) + credentials = get_credentials() + sample_run_report(credentials) + + # [END google_analytics_data_quickstart] if __name__ == "__main__": - main() + main() diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py index 46fa3d6..53db101 100644 --- a/samples/snippets/quickstart_oauth2_test.py +++ b/samples/snippets/quickstart_oauth2_test.py @@ -16,7 +16,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' + TEST_PROPERTY_ID = "222596558" quickstart_oauth2.sample_run_report(None, TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 7e1d307..b1e9caa 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -16,7 +16,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' + TEST_PROPERTY_ID = "222596558" quickstart.sample_run_report(TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out From 4d0a023ada6d37ba198c8d11eae685790c5bcddb Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Tue, 16 Mar 2021 23:39:14 -0700 Subject: [PATCH 10/14] fix: update formatting --- samples/snippets/quickstart.py | 19 +++-- .../snippets/quickstart_json_credentials.py | 47 ++++++----- .../quickstart_json_credentials_test.py | 12 +-- samples/snippets/quickstart_oauth2.py | 80 ++++++++++--------- samples/snippets/quickstart_oauth2_test.py | 2 +- samples/snippets/quickstart_test.py | 2 +- 6 files changed, 86 insertions(+), 76 deletions(-) diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 1d48a9e..68999a7 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -34,11 +34,11 @@ from google.analytics.data_v1beta.types import RunReportRequest -def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): +def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_initialize] # Using a default constructor instructs the client to use the credentials @@ -47,11 +47,12 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): # [END google_analytics_data_initialize] # [START google_analytics_data_run_report] - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) response = client.run_report(request) # [END google_analytics_data_run_report] @@ -62,8 +63,6 @@ def sample_run_report(property_id='YOUR-GA4-PROPERTY-ID'): # [END google_analytics_data_run_report_response] # [END google_analytics_data_quickstart] -def main(): - sample_run_report() if __name__ == "__main__": - main() + sample_run_report() diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 7181388..87f2a4d 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -34,32 +34,34 @@ from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest -def get_client(credentials_json_path=''): - """Creates an API client instance.""" - # [START google_analytics_data_initialize] - # TODO(developer): Uncomment this variable and replace with a valid path to - # the credentials.json file for your service account downloaded from the - # Cloud Console. - #credentials_json_path = '/path/to/credentials.json' - - # Explicitly use service account credentials by specifying - # the private key file. - return BetaAnalyticsDataClient().from_service_account_json( - credentials_json_path) - # [END google_analytics_data_initialize] - -def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): + +def get_client(credentials_json_path=""): + """Creates an API client instance.""" + # [START google_analytics_data_initialize] + # TODO(developer): Uncomment this variable and replace with a valid path to + # the credentials.json file for your service account downloaded from the + # Cloud Console. + # credentials_json_path = '/path/to/credentials.json' + + # Explicitly use service account credentials by specifying + # the private key file. + return BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) + # [END google_analytics_data_initialize] + + +def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = 'YOUR-GA4-PROPERTY-ID' # [START google_analytics_data_run_report] - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) response = client.run_report(request) # [END google_analytics_data_run_report] @@ -67,9 +69,12 @@ def sample_run_report(client, property_id='YOUR-GA4-PROPERTY-ID'): for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) + def main(): client = get_client() sample_run_report(client) + + # [END google_analytics_data_quickstart] if __name__ == "__main__": diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index 7181246..675106a 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -13,12 +13,14 @@ # limitations under the License. from google.analytics.data_v1beta import BetaAnalyticsDataClient + import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' - quickstart_json_credentials.sample_run_report(BetaAnalyticsDataClient(), - TEST_PROPERTY_ID) - out, _ = capsys.readouterr() - assert "Report result" in out + TEST_PROPERTY_ID = "222596558" + quickstart_json_credentials.sample_run_report( + BetaAnalyticsDataClient(), TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 40ab5de..3cef039 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -28,58 +28,62 @@ python3 quickstart_oauth2.py """ # [START google_analytics_data_quickstart] -from google_auth_oauthlib import flow - from google.analytics.data import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import DateRange from google.analytics.data_v1beta.types import Dimension from google.analytics.data_v1beta.types import Metric from google.analytics.data_v1beta.types import RunReportRequest +from google_auth_oauthlib import flow + +def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + # property_id = 'YOUR-GA4-PROPERTY-ID' -def sample_run_report(credentials=None, property_id='YOUR-GA4-PROPERTY-ID'): - """Runs a simple report on a Google Analytics 4 property.""" - # TODO(developer): Uncomment this variable and replace with your - # Google Analytics 4 property ID before running the sample. - #property_id = 'YOUR-GA4-PROPERTY-ID' + client = BetaAnalyticsDataClient(credentials=credentials) + request = RunReportRequest( + property="properties/" + str(property_id), + dimensions=[Dimension(name="city")], + metrics=[Metric(name="activeUsers")], + date_ranges=[DateRange(start_date="2020-03-31", end_date="today")], + ) - client = BetaAnalyticsDataClient(credentials=credentials) - request = RunReportRequest(property='properties/' + str(property_id), - dimensions=[Dimension(name='city')], - metrics=[Metric(name='activeUsers')], - date_ranges=[DateRange(start_date='2020-03-31', - end_date='today')]) + response = client.run_report(request) - response = client.run_report(request) + print("Report result:") + for row in response.rows: + print(row.dimension_values[0].value, row.metric_values[0].value) - print("Report result:") - for row in response.rows: - print(row.dimension_values[0].value, row.metric_values[0].value) def get_credentials(): - """Creates an OAuth2 credentials instance.""" - # [START google_analytics_data_initialize] - appflow = flow.InstalledAppFlow.from_client_secrets_file( - "client_secrets.json", - scopes=["https://www.googleapis.com/auth/analytics.readonly"] - ) - # TODO(developer): Update the line below to set the `launch_browser` variable. - # The `launch_browser` boolean variable indicates if a local server is used - # as the callback URL in the auth flow. A value of `True` is recommended, - # but a local server does not work if accessing the application remotely, - # such as over SSH or from a remote Jupyter notebook. - launch_browser = True - if launch_browser: - appflow.run_local_server() - else: - appflow.run_console() - return appflow.credentials - # [END google_analytics_data_initialize] + """Creates an OAuth2 credentials instance.""" + # [START google_analytics_data_initialize] + appflow = flow.InstalledAppFlow.from_client_secrets_file( + "client_secrets.json", + scopes=["https://www.googleapis.com/auth/analytics.readonly"], + ) + # TODO(developer): Update the line below to set the `launch_browser` variable. + # The `launch_browser` boolean variable indicates if a local server is used + # as the callback URL in the auth flow. A value of `True` is recommended, + # but a local server does not work if accessing the application remotely, + # such as over SSH or from a remote Jupyter notebook. + launch_browser = True + if launch_browser: + appflow.run_local_server() + else: + appflow.run_console() + return appflow.credentials + # [END google_analytics_data_initialize] + def main(): - credentials = get_credentials() - sample_run_report(credentials) + credentials = get_credentials() + sample_run_report(credentials) + + # [END google_analytics_data_quickstart] if __name__ == "__main__": - main() + main() diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py index 46fa3d6..53db101 100644 --- a/samples/snippets/quickstart_oauth2_test.py +++ b/samples/snippets/quickstart_oauth2_test.py @@ -16,7 +16,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' + TEST_PROPERTY_ID = "222596558" quickstart_oauth2.sample_run_report(None, TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 7e1d307..b1e9caa 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -16,7 +16,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = '222596558' + TEST_PROPERTY_ID = "222596558" quickstart.sample_run_report(TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out From e07dd3d75ea6840bad8f5ebf90eebc1b51aa1cc2 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Wed, 17 Mar 2021 12:42:40 -0700 Subject: [PATCH 11/14] add noxfile_config with a test property id value --- samples/snippets/noxfile_config.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 samples/snippets/noxfile_config.py diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py new file mode 100644 index 0000000..ad10f83 --- /dev/null +++ b/samples/snippets/noxfile_config.py @@ -0,0 +1,16 @@ +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {"TEST_PROPERTY_ID": "222596558"}, +} \ No newline at end of file From 618d2e7e03e4b049502917925a3406dd7ce70d40 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Wed, 17 Mar 2021 12:42:40 -0700 Subject: [PATCH 12/14] add noxfile_config with a test property id value --- samples/snippets/noxfile_config.py | 16 ++++++++++++++++ .../snippets/quickstart_json_credentials_test.py | 2 +- samples/snippets/quickstart_oauth2_test.py | 2 +- samples/snippets/quickstart_test.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 samples/snippets/noxfile_config.py diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py new file mode 100644 index 0000000..ad10f83 --- /dev/null +++ b/samples/snippets/noxfile_config.py @@ -0,0 +1,16 @@ +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {"TEST_PROPERTY_ID": "222596558"}, +} \ No newline at end of file diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index 171a688..0de3083 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -20,7 +20,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID", "222596558") + TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") quickstart_json_credentials.sample_run_report( BetaAnalyticsDataClient(), TEST_PROPERTY_ID ) diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py index ecdbc67..ab2ec9b 100644 --- a/samples/snippets/quickstart_oauth2_test.py +++ b/samples/snippets/quickstart_oauth2_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID", "222596558") + TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") quickstart_oauth2.sample_run_report(None, TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index a0b15b3..50bd6d9 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID", "222596558") + TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") quickstart.sample_run_report(TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out From 2b446afe4da2ef2656443da1b6648ff444a940a6 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Wed, 17 Mar 2021 16:20:20 -0700 Subject: [PATCH 13/14] fix: use the credentials json file provided during the test --- samples/snippets/noxfile_config.py | 2 +- samples/snippets/quickstart.py | 2 +- .../snippets/quickstart_json_credentials.py | 28 ++++++------------- .../quickstart_json_credentials_test.py | 9 +++--- samples/snippets/quickstart_oauth2.py | 2 +- samples/snippets/quickstart_oauth2_test.py | 2 +- samples/snippets/quickstart_test.py | 2 +- 7 files changed, 19 insertions(+), 28 deletions(-) diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py index 0badbd0..20c30ee 100644 --- a/samples/snippets/noxfile_config.py +++ b/samples/snippets/noxfile_config.py @@ -12,5 +12,5 @@ # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - "envs": {"TEST_PROPERTY_ID": "222596558"}, + "envs": {"GA_TEST_PROPERTY_ID": "222596558"}, } diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 57210ef..c3fe192 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -38,7 +38,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = "YOUR-GA4-PROPERTY-ID" # [START google_analytics_data_initialize] # Using a default constructor instructs the client to use the credentials diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 87f2a4d..92c24a8 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -35,26 +35,23 @@ from google.analytics.data_v1beta.types import RunReportRequest -def get_client(credentials_json_path=""): - """Creates an API client instance.""" +def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID", credentials_json_path=""): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + # property_id = "YOUR-GA4-PROPERTY-ID" + # [START google_analytics_data_initialize] # TODO(developer): Uncomment this variable and replace with a valid path to # the credentials.json file for your service account downloaded from the # Cloud Console. - # credentials_json_path = '/path/to/credentials.json' + # credentials_json_path = "/path/to/credentials.json" # Explicitly use service account credentials by specifying # the private key file. - return BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) + client = BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) # [END google_analytics_data_initialize] - -def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): - """Runs a simple report on a Google Analytics 4 property.""" - # TODO(developer): Uncomment this variable and replace with your - # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' - # [START google_analytics_data_run_report] request = RunReportRequest( property="properties/" + str(property_id), @@ -68,14 +65,7 @@ def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): print("Report result:") for row in response.rows: print(row.dimension_values[0].value, row.metric_values[0].value) - - -def main(): - client = get_client() - sample_run_report(client) - - # [END google_analytics_data_quickstart] if __name__ == "__main__": - main() + sample_run_report(client) diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index 0de3083..06d7d1e 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -14,15 +14,16 @@ import os -from google.analytics.data_v1beta import BetaAnalyticsDataClient - import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + # Create a temporary service account credentials JSON file to be used by + # the test. + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + CREDENTIALS_JSON_PATH = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") quickstart_json_credentials.sample_run_report( - BetaAnalyticsDataClient(), TEST_PROPERTY_ID + TEST_PROPERTY_ID, CREDENTIALS_JSON_PATH ) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 3cef039..4ef3228 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -40,7 +40,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = "YOUR-GA4-PROPERTY-ID" client = BetaAnalyticsDataClient(credentials=credentials) request = RunReportRequest( diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py index ab2ec9b..dcbdc19 100644 --- a/samples/snippets/quickstart_oauth2_test.py +++ b/samples/snippets/quickstart_oauth2_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") quickstart_oauth2.sample_run_report(None, TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 50bd6d9..14c639d 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") quickstart.sample_run_report(TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out From 7887b790cc67b342a9e2116810db179b9130a5d1 Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Wed, 17 Mar 2021 16:20:20 -0700 Subject: [PATCH 14/14] fix: use the credentials json file provided during the test --- samples/snippets/noxfile_config.py | 2 +- samples/snippets/quickstart.py | 2 +- .../snippets/quickstart_json_credentials.py | 26 +++++++------------ .../quickstart_json_credentials_test.py | 9 ++++--- samples/snippets/quickstart_oauth2.py | 2 +- samples/snippets/quickstart_oauth2_test.py | 2 +- samples/snippets/quickstart_test.py | 2 +- 7 files changed, 19 insertions(+), 26 deletions(-) diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py index 0badbd0..20c30ee 100644 --- a/samples/snippets/noxfile_config.py +++ b/samples/snippets/noxfile_config.py @@ -12,5 +12,5 @@ # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - "envs": {"TEST_PROPERTY_ID": "222596558"}, + "envs": {"GA_TEST_PROPERTY_ID": "222596558"}, } diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index 57210ef..c3fe192 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -38,7 +38,7 @@ def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = "YOUR-GA4-PROPERTY-ID" # [START google_analytics_data_initialize] # Using a default constructor instructs the client to use the credentials diff --git a/samples/snippets/quickstart_json_credentials.py b/samples/snippets/quickstart_json_credentials.py index 87f2a4d..858d150 100644 --- a/samples/snippets/quickstart_json_credentials.py +++ b/samples/snippets/quickstart_json_credentials.py @@ -35,26 +35,23 @@ from google.analytics.data_v1beta.types import RunReportRequest -def get_client(credentials_json_path=""): - """Creates an API client instance.""" +def sample_run_report(property_id="YOUR-GA4-PROPERTY-ID", credentials_json_path=""): + """Runs a simple report on a Google Analytics 4 property.""" + # TODO(developer): Uncomment this variable and replace with your + # Google Analytics 4 property ID before running the sample. + # property_id = "YOUR-GA4-PROPERTY-ID" + # [START google_analytics_data_initialize] # TODO(developer): Uncomment this variable and replace with a valid path to # the credentials.json file for your service account downloaded from the # Cloud Console. - # credentials_json_path = '/path/to/credentials.json' + # credentials_json_path = "/path/to/credentials.json" # Explicitly use service account credentials by specifying # the private key file. - return BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) + client = BetaAnalyticsDataClient().from_service_account_json(credentials_json_path) # [END google_analytics_data_initialize] - -def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): - """Runs a simple report on a Google Analytics 4 property.""" - # TODO(developer): Uncomment this variable and replace with your - # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' - # [START google_analytics_data_run_report] request = RunReportRequest( property="properties/" + str(property_id), @@ -70,12 +67,7 @@ def sample_run_report(client, property_id="YOUR-GA4-PROPERTY-ID"): print(row.dimension_values[0].value, row.metric_values[0].value) -def main(): - client = get_client() - sample_run_report(client) - - # [END google_analytics_data_quickstart] if __name__ == "__main__": - main() + sample_run_report(client) diff --git a/samples/snippets/quickstart_json_credentials_test.py b/samples/snippets/quickstart_json_credentials_test.py index 0de3083..06d7d1e 100644 --- a/samples/snippets/quickstart_json_credentials_test.py +++ b/samples/snippets/quickstart_json_credentials_test.py @@ -14,15 +14,16 @@ import os -from google.analytics.data_v1beta import BetaAnalyticsDataClient - import quickstart_json_credentials def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + # Create a temporary service account credentials JSON file to be used by + # the test. + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + CREDENTIALS_JSON_PATH = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") quickstart_json_credentials.sample_run_report( - BetaAnalyticsDataClient(), TEST_PROPERTY_ID + TEST_PROPERTY_ID, CREDENTIALS_JSON_PATH ) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_oauth2.py b/samples/snippets/quickstart_oauth2.py index 3cef039..4ef3228 100644 --- a/samples/snippets/quickstart_oauth2.py +++ b/samples/snippets/quickstart_oauth2.py @@ -40,7 +40,7 @@ def sample_run_report(credentials=None, property_id="YOUR-GA4-PROPERTY-ID"): """Runs a simple report on a Google Analytics 4 property.""" # TODO(developer): Uncomment this variable and replace with your # Google Analytics 4 property ID before running the sample. - # property_id = 'YOUR-GA4-PROPERTY-ID' + # property_id = "YOUR-GA4-PROPERTY-ID" client = BetaAnalyticsDataClient(credentials=credentials) request = RunReportRequest( diff --git a/samples/snippets/quickstart_oauth2_test.py b/samples/snippets/quickstart_oauth2_test.py index ab2ec9b..dcbdc19 100644 --- a/samples/snippets/quickstart_oauth2_test.py +++ b/samples/snippets/quickstart_oauth2_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") quickstart_oauth2.sample_run_report(None, TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 50bd6d9..14c639d 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -18,7 +18,7 @@ def test_quickstart(capsys): - TEST_PROPERTY_ID = os.getenv("TEST_PROPERTY_ID") + TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") quickstart.sample_run_report(TEST_PROPERTY_ID) out, _ = capsys.readouterr() assert "Report result" in out