I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?
views:
1145answers:
7This article outlines a few ways of detecting an iPhone through by checking the HTTP_USER_AGENT agent variable. Depending on where you want to do the check at (HTML level, Javascript, CSS, etc.), I'm sure you can extrapolate this into your Python app. Sorry, I'm not a python guy. 8^D
Check the user agent. It will be
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3
I'm not sure how to do this with appengine, but the equivalent PHP code can be found here: http://www.mattcutts.com/blog/iphone-user-agent/
Here's how to do implement it as middleware in Django, assuming that's what you're using on appengine.
class DetectiPhone(object):
def process_request(self, request):
if 'HTTP_USER_AGENT' in request.META and request.META['HTTP_USER_AGENT'].find('(iPhone') >= 0:
request.META['iPhone'] = True
Basically look for 'iPhone' in the HTTP_USER_AGENT. Note that iPod Touch has a slightly different signature than the iPhone, hence the broad 'iPhone' search instead of a more restrictive search.
if you're using the standard webapp framework the user agent will be in the request instance. This should be good enough:
if "iPhone" in request.headers["User-Agent"]:
# do iPhone logic
The Using the Safari on iPhone User Agent String article on the apple website indicate the different user agents for iPhone and iPod touch.
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3
Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_0 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/XXXXX Safari/525.20
import os
class MainPage(webapp.RequestHandler):
@login_required
def get(self):
userAgent = os.environ['HTTP_USER_AGENT']
if userAgent.find('iPhone') > 0:
self.response.out.write('iPhone support is coming soon...')
else:
self.response.out.write('Hey... you are not from iPhone...')
This is the syntax I was looking for, works with iphone and ipod touch:
uastring = self.request.headers.get('user_agent')
if "Mobile" in uastring and "Safari" in uastring:
# do iphone / ipod stuff