如果页面是通过iPhone/iPod Touch访问的,我需要以不同的方式呈现页面。 我想请求对象中包含这些信息,但语法是什么?
uastring = self.request.headers.get('user_agent')
if "Mobile" in uastring and "Safari" in uastring:
# do iphone / ipod stuff
苹果网站上的《使用iPhone Safari用户代理字符串》文章介绍了iPhone和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
这篇文章介绍了通过检查HTTP_USER_AGENT代理变量来检测iPhone的几种方法。根据您想在哪里进行检查(HTML级别、Javascript、CSS等),我相信您可以将其推广到您的Python应用程序中。抱歉,我不是Python专家。8^D
以下是如何在Django中将其实现为中间件的方法,假设您正在使用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
基本上在HTTP_USER_AGENT中查找“iPhone”。请注意,iPod Touch的签名与iPhone略有不同,因此使用广泛的“iPhone”搜索而不是更严格的搜索。
if "iPhone" in request.headers["User-Agent"]:
# do iPhone logic
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...')
检查用户代理。它将是
Mozilla/5.0(iPhone; U; CPU like Mac OS X; en)AppleWebKit/420+(KHTML,like Gecko)Version/3.0 Mobile/1A543a Safari/419.3
我不确定如何在appengine中实现这一点,但等效的PHP代码可以在此处找到:http://www.mattcutts.com/blog/iphone-user-agent/
AttributeError: 'WSGIRequest' object has no attribute 'headers'
的错误。 - noio