Skip to content

Instantly share code, notes, and snippets.

@anthonyeden
Created December 30, 2018 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyeden/12c20c826960b1a32bce3d58dcfe2bb6 to your computer and use it in GitHub Desktop.
Save anthonyeden/12c20c826960b1a32bce3d58dcfe2bb6 to your computer and use it in GitHub Desktop.
Google Analytics Realtime Data
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
VIEW_ID = 'ga:123456789'
def get_service(api_name, api_version, scope, key_file_location,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account p12 key file.
service_account_email: The service account email address.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_p12_keyfile(
service_account_email, key_file_location, scopes=scope)
http = credentials.authorize(httplib2.Http())
# Build the service object.
service = build(api_name, api_version, http=http)
return service
# Define the auth scopes to request.
scope = ['https://www.googleapis.com/auth/analytics.readonly']
# Use the developer console and replace the values with your
# service account email and relative location of your key file.
service_account_email = 'dashboard@dashboard.iam.gserviceaccount.com'
key_file_location = 'gakeyfile.p12'
# Authenticate and construct service.
service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)
# how many users are active now?
result = service.data().realtime().get(
ids=VIEW_ID,
metrics='rt:activeUsers',
dimensions='rt:medium').execute()
active_now = result['totalsForAllResults']['rt:activeUsers']
print("Active now: " + str(active_now))
# how many page views were there for the last 30 minutes?
result = service.data().realtime().get(
ids=VIEW_ID,
metrics='rt:pageviews',
dimensions='rt:minutesAgo').execute()
# 'rows' won't exist if there were no page views in the last 30 minutes
print(result['rows'])
Requirements:
- sudo pip install --upgrade google-api-python-client
Create a Service Account
1) Go to https://console.developers.google.com/permissions/serviceaccounts
2) Select a Project for the Service Account to created in (if you don't have a Project yet, click 'Create' and follow this process)
3) Click 'Create Service Account'
4) Type a name and also click 'Furnish a new private key'
5) Then choose 'P12' as the file Type
6) Click create and save the P12 file to your computer next to the Python script
Setup Analytics property
1) Navigate to your View in Analytics (under Admin)
2) Under the View, go to 'Users'
3) Add the Service Account you just created as a user (you can find the service account email address in the developer console. It will look something like test-7@dashboard-170303.iam.gserviceaccount.com)
4) Under the View, go to 'View Settings' and find the value of 'View ID'
In the Python script, replace these variables with the correct values:
- service_account_email
- key_file_location
- VIEW_ID
useful pages:
- https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get
- https://developers.google.com/analytics/devguides/reporting/realtime/dimsmets/
- some code from here: https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment