Tripleodeon

Python Google AdSense for Mobile code

I was amazed to discover that Google don’t currently support Python as a language for their mobile ads. AdMob doesn’t either (thinking it’s more likely that people might use perl or VBScript for a contemporary web site).

But it’s a particularly strange omission for Google, since it’s one of their three ‘official’ internal languages (together with Java and C++), and because their Google App Engine platform mandates it. Do they assume that no-one would create a mobile application in their cloud?

I don’t know – it’s probably just left-hand and right-hand out of sync.

Anyway, The Hollywood Walk of Fame mobile site has been a recent hobby for me, and I chose Django on Python for a bit of educational fun.

It was going well until I decided to throw some ads onto it.

So of course I needed to port the ad code. It’s very simple, although cuts a few corners (this does not support AdSense’s custom colour feature for example):

def google_ad(request, publisher_id, format='mobile_single'):
  scheme = 'https://' if request.is_secure() else 'http://'
  params = {
    'ad_type':'text_image',
    'channel':'',
    'client':'ca-mb-' + publisher_id,
    'dt':repr(floor(1000*time())),
    'format':format,
    'https':'on' if request.is_secure() else '',
    'host':scheme + request.META.get('HTTP_HOST', ''),
    'ip':request.META.get('REMOTE_ADDR', ''),
    'markup':'xhtml',
    'oe':'utf8',
    'output':'xhtml',
    'ref':request.META.get('HTTP_REFERER', ''),
    'url':scheme + request.META.get('HTTP_HOST', '') + \
          request.META.get('PATH_INFO', ''),
    'useragent':request.META.get('HTTP_USER_AGENT', '')
  }
  screen_res = request.META.get('HTTP_UA_PIXELS', '')
  delimiter = 'x'
  if screen_res == '':
    screen_res = request.META.get('HTTP_X_UP_DEVCAP_SCREENPIXELS', '')
    delimiter = ','
  res_array = screen_res.split(delimiter)
  if len(res_array) == 2:
    params['u_w'] = res_array[0]
    params['u_h'] = res_array[1]
  dcmguid = request.META.get('HTTP_X_DCMGUID', '')
  if dcmguid != '':
    params['dcmguid'] = dcmguid
  url = 'http://pagead2.googlesyndication.com/pagead/ads?' + urlencode(params)
  return urlopen(url).read()

 

I presume I’m allowed to do this, I know it’s only 15 minutes saved – but if it helps someone, great. No warranties – but it works for me!

Incidentally, in Django, I am placing this in a context_processor so that it gets put into a template variable that I know will turn up in every view when the site is in mobile ‘mode’. I use a switcher like this to toggle between http://hwof.com and http://hwof.mobi.

Hm. This post looks terrible in this theme. I think I need to change WordPress template soon.