Skip to content

Instantly share code, notes, and snippets.

@canburak
Last active February 13, 2021 23:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save canburak/1593381 to your computer and use it in GitHub Desktop.
Save canburak/1593381 to your computer and use it in GitHub Desktop.
blog post: Push data to Google Analytics with Python: https://medium.com/p/pushing-data-to-google-analytics-with-python-80eb9691d61f
"""
Simple proof of concept code to push data to Google Analytics.
Related blog post:
* https://medium.com/python-programming-language/80eb9691d61f
"""
from random import randint
from urllib import urlencode
from urllib2 import urlopen
from urlparse import urlunparse
from hashlib import sha1
from os import environ
# Set your proprty id via the environment or simply type it
# below
PROPERTY_ID = environ.get("GA_PROPERTY_ID", "UA-xxxxx-xx")
# Generate the visitor identifier somehow. I get it from the
# environment, calculate the SHA1 sum of it, convert this from base 16
# to base 10 and get first 10 digits of this number.
VISITOR = environ.get("GA_VISITOR", "xxxxx")
VISITOR = str(int("0x%s" % sha1(VISITOR).hexdigest(), 0))[:10]
# The path to visit
PATH = "/sample/path/"
# Collect everything in a dictionary
DATA = {"utmwv": "5.2.2d",
"utmn": str(randint(1, 9999999999)),
"utmp": PATH,
"utmac": PROPERTY_ID,
"utmcc": "__utma=%s;" % ".".join(["1", VISITOR, "1", "1", "1", "1"])}
# Encode this data and generate the final URL
URL = urlunparse(("http",
"www.google-analytics.com",
"/__utm.gif",
"",
urlencode(DATA),
""))
# Make the request
print "Requesting", URL
print urlopen(URL).info()
@grantjenks
Copy link

There's also a good reference at https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide . I'm not sure how these compare.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment