为什么Python会在非迭代类型的操作中给我一个"TypeError:类型'UserAgent'的参数不可迭代"?

tom*_*yes 1 python google-app-engine tipfy

我有一个BaseHandler类,它在我的AppEngine站点中继承了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
Run Code Online (Sandbox Code Playgroud)

这是Python不喜欢的行:

File "/path/to/project/app/apps/remember_things/handlers.py", line 56, in detect_mobile_devices
if device in self.request.user_agent:
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 5

表达方式

device in self.request.user_agent
Run Code Online (Sandbox Code Playgroud)

将首先尝试打电话

self.request.user_agent.__contains__(device)
Run Code Online (Sandbox Code Playgroud)

如果此方法不存在,Python会尝试迭代self.request.user_agent并比较它遇到的每个项目device.显然,self.request.user_agent既不允许.__contains__()也不迭代,因此错误消息.

另请参阅Python中的成员资格测试文档.