我用Flask写了一个网站;它会为移动设备和桌面返回不同的结果。我在服务器上使用request.user_agent.platform
检查平台。
这是我为Android,桌面和其他移动设备返回不同网站的代码:
if request.user_agent.platform == "android":
ismobile = True
# do something when the user is on android
for pf in ["iphone", "iPad", "ipad", "Windows Phone OS", "windows phone os", "BlackBerry", "windows phone", "Windows Phone", "WindowsPhone", "android"]:
if pf in request.user_agent.platform:
ismobile = True
# do something when the user is on any other mobile device
if not ismobile:
# do something when the user is on desktop
到目前为止,此代码有效。但是当Google-Bot发送请求时,会抛出ValueError:
TypeError
TypeError: argument of type 'NoneType' is not iterable
(使用Google标记工具测试,此处为full stack trace)。
当Google访问我的网页时,似乎某些内容为“无”。有谁知道我怎么能阻止我的应用程序抛出错误?
编辑:我忘了:访问请求时会抛出错误。像if request is None:
这样的代码仍会产生错误。
答案 0 :(得分:1)
此处抛出错误:
if pf in request.user_agent.platform:
其中platform
应该是支持包含测试的对象。 None
不是这样的对象,所以明确地测试它:
platform = request.user_agent.platform
if platform and pf in platform: