Wednesday, February 03, 2010

Detecting iPhone/iPod/iPad clients on Google App engine

Recently, while working on a fun little side project (, we needed to detect and render a very different page for iPhone users (no Flash and slightly different page structure to accommodate iPhone copy&paste)

When the iPhone (or iPod/iPad) requests a url, it includes a user-agent string like the following:

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

To detect and parse that from a webapp-based application on appengine, just do the following:

import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

class MainPage(webapp.RequestHandler):
def get(self):
user_agent = self.request.headers.get('User-Agent', '').lower()
iphone = 'iphone' in user_agent or 'ipod' in user_agent

if iphone:

application = webapp.WSGIApplication([('/', MainPage)], debug=True)

def main():

if __name__ == "__main__":

Of course you can do something more sophisticated like parsing and rendering templates differently, but this is just an example.

A quick way to test it out is launch Safari, go to Develop->User Agent->Other, and pop-in the user-agent string at the top of this blog entry. Be sure to test it out on the simulator or the actual device since screen size will affect rendering as well.


Dave said...

If you are specifically targeting an iphone app (versus an iphone webkit, and I'd assume similarly for the upcoming ipad), then you'll notice that it has "iphone os" and "applewebkit" in the user agent string, but not "safari". Check against the safari to target an iphone app versus the iphone webkit.

Michael said...

I found an iPad detect and redirect here

Edie Jams said...

In modern era, iPhone is playing vital role in versatile businesses because all businesses are going too shifted on online. Now iPad apps development also becomes part of this core business.

online brand marketing agency | singapore brand marketing agency