Last active
January 22, 2018 13:23
-
-
Save robhammond/4f8eded2f2349b383c9466ab4d0a9c4c to your computer and use it in GitHub Desktop.
Add Google Analytics users in batch for a list of specified properties and views using the Python Management API
This file contains hidden or 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
"""A simple example of Google Analytics batched user permissions.""" | |
"""https://developers.google.com/analytics/devguides/config/mgmt/v3/user-management#batching""" | |
import argparse | |
from apiclient.discovery import build | |
from oauth2client.service_account import ServiceAccountCredentials | |
import httplib2 | |
from oauth2client import client | |
from oauth2client import file | |
from oauth2client import tools | |
import json | |
from apiclient.errors import HttpError | |
from apiclient.http import BatchHttpRequest | |
def get_service(api_name, api_version, scopes, client_secrets_path): | |
"""Get a service that communicates to a Google API. | |
Args: | |
api_name: string The name of the api to connect to. | |
api_version: string The api version to connect to. | |
scope: A list of strings representing the auth scopes to authorize for the | |
connection. | |
client_secrets_path: string A path to a valid client secrets file. | |
Returns: | |
A service that is connected to the specified API. | |
""" | |
# Parse command-line arguments. | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
parents=[tools.argparser]) | |
flags = parser.parse_args([]) | |
# Set up a Flow object to be used if we need to authenticate. | |
flow = client.flow_from_clientsecrets( | |
client_secrets_path, scope=scopes, | |
message=tools.message_if_missing(client_secrets_path)) | |
# Prepare credentials, and authorize HTTP object with them. | |
# If the credentials don't exist or are invalid run through the native client | |
# flow. The Storage object will ensure that if successful the good | |
# credentials will get written back to a file. | |
storage = file.Storage(api_name + '.dat') | |
credentials = storage.get() | |
if credentials is None or credentials.invalid: | |
credentials = tools.run_flow(flow, storage, flags) | |
http = credentials.authorize(http=httplib2.Http()) | |
# Build the service object. | |
service = build(api_name, api_version, http=http) | |
return service | |
def call_back(request_id, response, exception): | |
"""Handle batched request responses.""" | |
print request_id | |
if exception is not None: | |
if isinstance(exception, HttpError): | |
message = json.loads(exception.content)['error']['message'] | |
print ('Request %s returned API error : %s : %s ' % | |
(request_id, exception.resp.status, message)) | |
else: | |
print response | |
def add_users(users, permissions, account_id, profiles): | |
"""Adds users to every view (profile) with the given permissions. | |
Args: | |
users: A list of user email addresses. | |
permissions: A list of user permissions. | |
account_id: GA account ID | |
profiles: A list of properties & profiles. | |
Note: this code assumes you have MANAGE_USERS level permissions | |
to each profile and an authorized Google Analytics service object. | |
""" | |
# Define the auth scopes to request. | |
scopes = ['https://www.googleapis.com/auth/analytics.manage.users.readonly', | |
'https://www.googleapis.com/auth/analytics.manage.users', | |
'https://www.googleapis.com/auth/analytics.readonly'] | |
# Authenticate and construct service. | |
analytics = get_service('analytics', 'v3', scopes, 'client_secrets.json') | |
# Loop through each user. | |
for user in users: | |
# Create the BatchHttpRequest object. | |
batch = BatchHttpRequest(callback=call_back) | |
# Loop through each profile. | |
for i in profiles: | |
link = analytics.management().profileUserLinks().insert( | |
accountId=account_id, | |
webPropertyId=i['property'], | |
profileId=i['view'], | |
body={ | |
'permissions': { | |
'local': permissions | |
}, | |
'userRef': { | |
'email': user | |
} | |
} | |
) | |
batch.add(link) | |
# Execute the batch request for each user. | |
batch.execute() | |
if __name__ == '__main__': | |
# Construct a list of users. | |
emails = ['[email protected]'] | |
# Google Analytics Account ID | |
account_id = '123456' | |
# Array containing dict of required property & view access | |
profiles = [ | |
{'property': 'UA-xxxxxxxxx-xx', 'view': 123456789}, | |
] | |
# call the add_users function with the list of desired permissions. | |
add_users(emails, ['READ_AND_ANALYZE'], account_id, profiles) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment