Skip to content

Instantly share code, notes, and snippets.

@jasonrdsouza
Created June 20, 2014 18:17
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 jasonrdsouza/39d64c36f4f87802b6c8 to your computer and use it in GitHub Desktop.
Save jasonrdsouza/39d64c36f4f87802b6c8 to your computer and use it in GitHub Desktop.
Snippet to send events to Google Analytics from an AppEngine instance
import urllib
from google.appengine.api import urlfetch
# Set this to the specific Google Analytics Tracking Id for your application.
GA_TRACKING_ID = "UA-XXXX-Y"
GA_CLIENT_ID = "555"
def track_event_to_ga(category, action, label=None, value=None):
""" Posts an Event Tracking message to Google Analytics. """
form_fields = {
"v": "1", # Version.
"tid": GA_TRACKING_ID, # Tracking ID / Web property / Property ID.
"cid": GA_CLIENT_ID, # Anonymous Client ID.
"t": "event", # Event hit type.
"ec": category, # Event Category. Required.
"ea": action, # Event Action. Required.
"el": label, # Event label.
"ev": value, # Event value.
}
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url="http://www.google-analytics.com/collect",
payload=form_data,
method=urlfetch.POST,
headers={"Content-Type": "application/x-www-form-urlencoded"})
return result.status_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment