Created
May 8, 2019 13:28
-
-
Save thinkallabout/370d2ec1f2002eb5140ef013a292a5d8 to your computer and use it in GitHub Desktop.
Post to Google Analytics Measurement Protocol with this Python function
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
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