Created
August 22, 2022 00:53
-
-
Save wolz-CODElife/1b39007046a49a0c1649ba27bf2104bf to your computer and use it in GitHub Desktop.
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
"""Hello Analytics Reporting API V4.""" | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
from apiclient.discovery import build | |
from oauth2client.service_account import ServiceAccountCredentials | |
import requests, json | |
import dataframe_image as dfi | |
import cloudinary | |
import cloudinary.uploader | |
import cloudinary.api | |
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] | |
KEY_FILE_LOCATION = "PATH_TO_ANALYTICS_API_KEY_JSON_FILE" | |
VIEW_ID = 'VIEW_ID' | |
cloudinary.config( | |
cloud_name = "CLOUDINARY_LIBRARY_NAME", | |
api_key = "CLOUDINARY_API_KEY", | |
api_secret = "CLOUDINARY_API_SECRET_KEY" | |
) | |
def ga_response_dataframe(response): | |
row_list = [] | |
# Get each collected report | |
for report in response.get('reports', []): | |
# Set column headers | |
column_header = report.get('columnHeader', {}) | |
dimension_headers = column_header.get('dimensions', []) | |
metric_headers = column_header.get('metricHeader', {}).get('metricHeaderEntries', []) | |
# Get each row in the report | |
for row in report.get('data', {}).get('rows', []): | |
# create dict for each row | |
row_dict = {} | |
dimensions = row.get('dimensions', []) | |
date_range_values = row.get('metrics', []) | |
# Fill dict with dimension header (key) and dimension value (value) | |
for header, dimension in zip(dimension_headers, dimensions): | |
row_dict[header] = dimension | |
# Fill dict with metric header (key) and metric value (value) | |
for i, values in enumerate(date_range_values): | |
for metric, value in zip(metric_headers, values.get('values')): | |
# Set int as int, float a float | |
if ',' in value or '.' in value: | |
row_dict[metric.get('name')] = float(value) | |
else: | |
row_dict[metric.get('name')] = int(value) | |
row_list.append(row_dict) | |
return pd.DataFrame(row_list) | |
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:browser"} | |
] | |
}] | |
} | |
).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) | |
def main(): | |
analytics = initialize_analyticsreporting() | |
response = get_report(analytics) | |
TOKEN = "WPGRAPHQL_AUTH_TOKEN" | |
WPGRAPHQL_ENDPOINT = "WPGRAPHQL_ENDPOINT" | |
content_data= str(response) | |
plt.style.use('ggplot') | |
df = ga_response_dataframe(response) | |
# Pivot table to have browsers as columns | |
df.set_index('ga:browser', inplace=True) | |
axes = df.plot(kind='pie', figsize=(12.5, 6), subplots=True, legend=False) | |
plt.savefig('df3.png') | |
upload_result = cloudinary.uploader.upload("PATH_TO_LOCAL_IMAGE_FILE") | |
upload_url = upload_result["secure_url"] | |
headers = { | |
"Content-Type": "application/json", | |
"Authorization": 'Bearer ' + TOKEN | |
} | |
mutation = """ | |
mutation CreateIllustration { | |
createMediaItem( | |
input: {title: "Plot", | |
filePath: %s, | |
} | |
) { | |
clientMutationId | |
} | |
} | |
""" % json.dumps(upload_url) | |
data = (requests.post(WPGRAPHQL_ENDPOINT, json={'query': mutation}, headers=headers).json()) | |
print(data) | |
print_response(response) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment