-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,78 +1,59 @@ | ||
"""Hello Analytics Reporting API V4.""" | ||
|
||
from apiclient.discovery import build | ||
from oauth2client.service_account import ServiceAccountCredentials | ||
|
||
|
||
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] | ||
KEY_FILE_LOCATION = 'key.json' | ||
VIEW_ID = '3535025389' | ||
|
||
|
||
def initialize_analyticsreporting(): | ||
"""Initializes an Analytics Reporting API V4 service object. | ||
Returns: | ||
An authorized Analytics Reporting API V4 service object. | ||
""" | ||
credentials = ServiceAccountCredentials.from_json_keyfile_name( | ||
KEY_FILE_LOCATION, SCOPES) | ||
|
||
# Build the service object. | ||
analytics = build('analyticsreporting', 'v4', credentials=credentials) | ||
|
||
return analytics | ||
|
||
|
||
def get_report(analytics): | ||
"""Queries the Analytics Reporting API V4. | ||
Args: | ||
analytics: An authorized Analytics Reporting API V4 service object. | ||
Returns: | ||
The Analytics Reporting API V4 response. | ||
""" | ||
return analytics.reports().batchGet( | ||
body={ | ||
'reportRequests': [ | ||
{ | ||
'viewId': VIEW_ID, | ||
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], | ||
'metrics': [{'expression': 'ga:sessions'}], | ||
'dimensions': [{'name': 'ga:country'}] | ||
}] | ||
} | ||
).execute() | ||
|
||
|
||
def print_response(response): | ||
"""Parses and prints the Analytics Reporting API V4 response. | ||
Args: | ||
response: An Analytics Reporting API V4 response. | ||
""" | ||
for report in response.get('reports', []): | ||
columnHeader = report.get('columnHeader', {}) | ||
dimensionHeaders = columnHeader.get('dimensions', []) | ||
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) | ||
|
||
for row in report.get('data', {}).get('rows', []): | ||
dimensions = row.get('dimensions', []) | ||
dateRangeValues = row.get('metrics', []) | ||
|
||
for header, dimension in zip(dimensionHeaders, dimensions): | ||
print(header + ': ', dimension) | ||
|
||
for i, values in enumerate(dateRangeValues): | ||
print('Date range:', str(i)) | ||
for metricHeader, value in zip(metricHeaders, values.get('values')): | ||
print(metricHeader.get('name') + ':', value) | ||
|
||
from google.analytics.data_v1beta import BetaAnalyticsDataClient | ||
from google.analytics.data_v1beta.types import * | ||
from google.oauth2 import service_account | ||
|
||
|
||
def sample_run_report(client, property_id): | ||
request = RunReportRequest( | ||
property=f"properties/{property_id}", | ||
dimensions=[Dimension(name="customUser:user_group")], | ||
metrics=[Metric(name="activeUsers")], | ||
date_ranges=[DateRange(start_date="2022-09-18", end_date="today")], | ||
) | ||
response = client.run_report(request) | ||
|
||
print("Report result:") | ||
for dimension_header in response.dimension_headers: | ||
print(dimension_header.name, end="\t") | ||
|
||
for metric_header in response.metric_headers: | ||
print(metric_header.name, end="\n") | ||
|
||
for row in response.rows: | ||
rowString = '' | ||
for dimension in row.dimension_values: | ||
rowString += f"{dimension.value}\t\t" | ||
for metric in row.metric_values: | ||
rowString += f"{metric.value}\t\t" | ||
print(rowString) | ||
|
||
def sample_run_relatime_report(client: BetaAnalyticsDataClient, property_id): | ||
request = RunRealtimeReportRequest( | ||
property=f"properties/{property_id}", | ||
dimensions=[Dimension(name="customUser:user_group")], | ||
metrics=[Metric(name="activeUsers")], | ||
) | ||
response: RunRealtimeReportResponse = client.run_realtime_report(request) | ||
|
||
print("Realtime report result:") | ||
for dimension_header in response.dimension_headers: | ||
print(dimension_header.name, end="\t") | ||
|
||
for metric_header in response.metric_headers: | ||
print(metric_header.name, end="\t\n") | ||
|
||
for row in response.rows: | ||
rowString = '' | ||
for dimension in row.dimension_values: | ||
rowString += f"{dimension.value}\t" | ||
for metric in row.metric_values: | ||
rowString += f"{metric.value}\t" | ||
print(rowString) | ||
|
||
def main(): | ||
analytics = initialize_analyticsreporting() | ||
response = get_report(analytics) | ||
print_response(response) | ||
|
||
credentials = service_account.Credentials.from_service_account_file(".\pedagogic-ide-a137fcb189d5.json") | ||
client = BetaAnalyticsDataClient(credentials=credentials) | ||
# sample_run_report(client, "313384509") | ||
sample_run_relatime_report(client, "313384509") | ||
if __name__ == '__main__': | ||
main() |