Skip to content

Instantly share code, notes, and snippets.

@thinkallabout
Created May 8, 2019 13:28
Show Gist options
  • Save thinkallabout/370d2ec1f2002eb5140ef013a292a5d8 to your computer and use it in GitHub Desktop.
Save thinkallabout/370d2ec1f2002eb5140ef013a292a5d8 to your computer and use it in GitHub Desktop.
Post to Google Analytics Measurement Protocol with this Python function
def track_event(category, action, label=None, value=0):
data = {
'v': '1', # API Version.
'tid': GA_TRACKING_ID, # Tracking ID / Property ID.
# Anonymous Client Identifier. Ideally, this should be a UUID that
# is associated with particular user, device, or browser instance.
'cid': '555',
't': 'event', # Event hit type.
'ec': category, # Event category.
'ea': action, # Event action.
'el': label, # Event label.
'ev': value, # Event value, must be an integer
}
response = requests.post(
'https://www.google-analytics.com/collect', data=data)
# If the request fails, this will raise a RequestException. Depending
# on your application's needs, this may be a non-error and can be caught
# by the caller.
response.raise_for_status()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment