我在AppEngine网站中有一个BaseHandler类,该类继承了Tipfy RequestHandler。在其中,我为带有设备名称的类属性(元组)的移动设备设置了“穷人”浏览器嗅探器。
在随后的方法中,我遍历元组中的设备名称,并根据Request对象中的用户代理字符串检查它们。如果找到匹配项,则将一个名为“ is_mobile”的实例属性设置为True。
但是,在该方法中,Python给了我一个“ TypeError:类型'UserAgent'的参数是不可迭代的”错误,并且我不明白为什么,因为它抱怨的行不是(据我所知)一个循环。
这是代码:
class BaseHandler(RequestHandler, AppEngineAuthMixin, AllSessionMixins):
mobile_devices = ('Android', 'iPhone', 'iPod', 'Blackberry')
....
def detect_mobile_devices(self):
found_device = False
for device in self.__class__.mobile_devices:
if device in self.request.user_agent:
found_device = True
break
self.is_mobile = found_device
这是Python不喜欢的行:
File "/path/to/project/app/apps/remember_things/handlers.py", line 56, in detect_mobile_devices
if device in self.request.user_agent:
最佳答案
表达方式
device in self.request.user_agent
首先会尝试致电
self.request.user_agent.__contains__(device)
如果此方法不存在,Python将尝试遍历
self.request.user_agent
并将其遇到的每个项目与device
进行比较。显然,self.request.user_agent
的类型既不允许.__contains__()
也不允许迭代,因此会出现错误消息。另请参见the documentation of membership test in Python。