Skip to content

Instantly share code, notes, and snippets.

@iosiuk
Last active December 8, 2018 18:47
Show Gist options
  • Select an option

  • Save iosiuk/1608fc6fe9d905f61e6abe8568144ab1 to your computer and use it in GitHub Desktop.

Select an option

Save iosiuk/1608fc6fe9d905f61e6abe8568144ab1 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First of all, you must have a project in the Google API Console with enabling the Analytics API and credentials. Not ready yet? Read [Google's instructions](https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/installed-py?hl=en#enable).\n",
"\n",
"Of cource, you must have a [Jupyter Notebook](http://jupyter.org/install) and installed Google Client Library. If you have no Jupyter Notebook — you can install [Anaconda](https://www.anaconda.com/download/). For instalition libraries you can use [Google's instructions](https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/installed-py?hl=en#install) or [Anaconda's instructions](https://anaconda.org/conda-forge/google-api-python-client).\n",
"\n",
"Let's get started!\n",
"\n",
"Library initialization:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"import argparse\n",
"\n",
"from apiclient.discovery import build\n",
"import httplib2\n",
"from oauth2client import client\n",
"from oauth2client import file\n",
"from oauth2client import tools"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define authorization function:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"def get_service(api_name, api_version, scope, client_secrets_path):\n",
" \"\"\"Get a service that communicates to a Google API.\n",
"\n",
" Args:\n",
" api_name: string The name of the api to connect to.\n",
" api_version: string The api version to connect to.\n",
" scope: A list of strings representing the auth scopes to authorize for the\n",
" connection.\n",
" client_secrets_path: string A path to a valid client secrets file.\n",
"\n",
" Returns:\n",
" A service that is connected to the specified API.\n",
" \"\"\"\n",
" # Parse command-line arguments.\n",
" parser = argparse.ArgumentParser(\n",
" formatter_class=argparse.RawDescriptionHelpFormatter,\n",
" parents=[tools.argparser])\n",
" flags = parser.parse_args([])\n",
"\n",
" # Set up a Flow object to be used if we need to authenticate.\n",
" flow = client.flow_from_clientsecrets(\n",
" client_secrets_path, scope=scope,\n",
" message=tools.message_if_missing(client_secrets_path))\n",
"\n",
" # Prepare credentials, and authorize HTTP object with them.\n",
" # If the credentials don't exist or are invalid run through the native client\n",
" # flow. The Storage object will ensure that if successful the good\n",
" # credentials will get written back to a file.\n",
" storage = file.Storage(api_name + '.dat')\n",
" credentials = storage.get()\n",
" if credentials is None or credentials.invalid:\n",
" credentials = tools.run_flow(flow, storage, flags)\n",
" http = credentials.authorize(http=httplib2.Http())\n",
"\n",
" # Build the service object.\n",
" service = build(api_name, api_version, http=http)\n",
"\n",
" return service"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define exclude query parameters function:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def exclude_query_parameters(service, query, profile_element):\n",
" profile_id = profile_element.get('id')\n",
" account_id = profile_element.get('accountId')\n",
" property_id = profile_element.get('webPropertyId')\n",
" if profile_element.get('type') == 'WEB':\n",
" if profile_element.get('excludeQueryParameters'):\n",
" if query in profile_element['excludeQueryParameters']:\n",
" print('URL parameter {} already exist in View: '\n",
" '{} (Property: {}, Account:{})'.format(\n",
" query, profile_id, property_id, account_id))\n",
" return\n",
"\n",
" query_parameters = '{},{}'.format(\n",
" profile_element['excludeQueryParameters'], query)\n",
" else:\n",
" query_parameters = query\n",
"\n",
" profile_element['excludeQueryParameters'] = query_parameters\n",
" service.management().profiles().update(\n",
" accountId=account_id,\n",
" webPropertyId=property_id,\n",
" profileId=profile_id,\n",
" body=profile_element\n",
" ).execute()\n",
" print(\n",
" 'Successfully update View: {} (Property: {}, Account:{})'.format(\n",
" profile_id,property_id,account_id))\n",
" else:\n",
" print('In APP view no opportunity to update excludeQueryParameters. '\n",
" 'View: {} (Property: {}, Account:{})'.format(\n",
" profile_id, property_id,account_id))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Main code, authentication and updation all GA views in Google-account:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Your browser has been opened to visit:\n",
"\n",
" https://accounts.google.com/o/oauth2/auth?client_id=***********&redirect_uri=*********&scope=****************&access_type=offline&response_type=code\n",
"\n",
"If your browser is on a different machine then exit and re-run this\n",
"application with the command-line parameter\n",
"\n",
" --noauth_local_webserver\n",
"\n",
"Authentication successful.\n",
"Successfully update View: 138302000 (Property: UA-69959157-4, Account:69959157)\n",
"URL parameter fbclid already exist in View: 178122842 (Property: UA-69959157-4, Account:69959157)\n",
"End of updating process. Subscribe my Telegram-channel: https://t.me/webanalyst\n"
]
}
],
"source": [
"# Set url parameter to add it in excludeQueryParameters\n",
"# and exception IDs of accounts, properties and profiles.\n",
"url_parameter = 'fbclid'\n",
"exception_accounts = ['123456789', '987654321']\n",
"exception_properties = ['UA-123456789-1','UA-987654321-1']\n",
"exception_profiles = ['11111','22222']\n",
"\n",
"# Define the auth scopes to request.\n",
"scope = ['https://www.googleapis.com/auth/analytics.edit']\n",
"# Authenticate and construct service.\n",
"service = get_service('analytics', 'v3', scope, 'client_secrets.json')\n",
"# Get list of GA accounts.\n",
"accounts = service.management().accounts().list().execute()\n",
"\n",
"# Update all views.\n",
"if not accounts.get('items'):\n",
" print(\"Your Google-account have no any Google Analytics accounts.\")\n",
" exit(0)\n",
" \n",
"for account_element in accounts.get('items'):\n",
" account_id = account_element.get('id')\n",
" if account_id in exception_accounts:\n",
" continue\n",
"\n",
" properties = service\\\n",
" .management()\\\n",
" .webproperties()\\\n",
" .list(accountId=account_id)\\\n",
" .execute()\n",
" for property_element in properties.get('items'):\n",
" property_id = property_element.get('id')\n",
" if property_id in exception_properties:\n",
" continue\n",
"\n",
" profiles = service\\\n",
" .management()\\\n",
" .profiles()\\\n",
" .list(accountId=account_id, webPropertyId=property_id)\\\n",
" .execute()\n",
" for profile_element in profiles.get('items'):\n",
" profile_id = profile_element.get('id')\n",
" if profile_id in exception_profiles:\n",
" continue\n",
"\n",
" try:\n",
" exclude_query_parameters(\n",
" service,\n",
" url_parameter,\n",
" profile_element\n",
" )\n",
" except Exception:\n",
" print(\"Error: probably, your account have no permissions \"\n",
" \"for editing view's settings. View: \"\n",
" \"{} (Property: {}, Account:{})\".format(\n",
" profile_id, property_id, account_id))\n",
"\n",
"print('End of updating process. Subscribe my '\n",
" 'Telegram-channel: https://t.me/webanalyst')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment