Skip to content

Instantly share code, notes, and snippets.

@MarkEdmondson1234
Created November 23, 2014 13:01
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 MarkEdmondson1234/99133e04086565ce50be to your computer and use it in GitHub Desktop.
Save MarkEdmondson1234/99133e04086565ce50be to your computer and use it in GitHub Desktop.
def getUniqueClientId(seed=''):
"""Function to create the cid from the parameter passed in. Change this as needed """
if seed: random.seed(seed)
## make this so its always unique by referring to a set or using md5 or something
theID = str(random.randint(1,9999)).zfill(4) + "-" + str(random.randint(1,9999)).zfill(4) + "-" + str(random.randint(1,9999)).zfill(4) + "-" + str(random.randint(1,9999)).zfill(4)
return theID
class ImageRequest(blobstore_handlers.BlobstoreDownloadHandler):
"""The image that is in the email, and has a unique ID attached to it"""
"""This is called when the image is viewed, say in an email or another website"""
def get(self):
p = cgi.escape(self.request.get('p'))
c = cgi.escape(self.request.get('c'))
cid = cgi.escape(self.request.get('cid'))
nohit = cgi.escape(self.request.get('nohit'))
## if it has the same seed, creates an id like xxxx-xxxx-xxxx-xxxx
cid = getUniqueClientId(cid)
## construct the Measurement Protocol call
ga_url_stem = "http://www.google-analytics.com/collect"
## refer to https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
values = {'v' : 1,
'tid' : 'UA-54019251-3', ## replace with your GA ID
'cid' : cid}
if p: ## make a pageview when people see the image
values['t'] = 'pageview'
values['dh'] = 'external_email'
values['ec'] = 'email'
values['ea'] = 'open'
else: ## else make an event
values['t'] = 'event'
values['ec'] = 'email'
values['ea'] = 'open'
if c: ## put campaign info in the pageview
values['el'] = c
values['dp'] = '/vpv/email-view/' + c
else: ## put campaign info in the event labels
values['el'] = "campaign_name"
values['dp'] = '/vpv/email-view'
### z is the cache buster
values['z'] = str(random.randint(1,999999)).zfill(6)
if not nohit: ## nohit=1 if you don't want to send hit to GA
### send the hit to Google as a POST
data = urllib.urlencode(values)
req = urllib2.Request(ga_url_stem, data)
response = urllib2.urlopen(req)
the_page = response.read()
print values ## look in logs to see what was sent
### get the image upload previously done at /upload-image.html and stored in datastore
pixel = Pixel.get_by_id("image")
### serve up image
if pixel:
img = blobstore.BlobInfo.get(pixel.img)
self.send_blob(img)
else:
self.response.out.write("no image")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment