【发布时间】:2012-02-02 20:34:50
【问题描述】:
我需要检测 3 种类型的设备:tablet、mobile 或 desktop。
我找到了一个检测手机on github的脚本,但是我如何检测手机、平板和台式机呢?
【问题讨论】:
我需要检测 3 种类型的设备:tablet、mobile 或 desktop。
我找到了一个检测手机on github的脚本,但是我如何检测手机、平板和台式机呢?
【问题讨论】:
根据您之前使用的移动检测中间件,我建议您:
选择Python port of MobileESP (source code here) 并将其放入项目底部名为mobileesp 的文件夹中(manage.py 所在的位置)。放入一个空白的__init__.py 文件,以便 Python 将其视为一个包。
继续在该目录中创建一个新文件middleware.py,并填写:
import re
from mobileesp import mdetect
class MobileDetectionMiddleware(object):
"""
Useful middleware to detect if the user is
on a mobile device.
"""
def process_request(self, request):
is_mobile = False
is_tablet = False
is_phone = False
user_agent = request.META.get("HTTP_USER_AGENT")
http_accept = request.META.get("HTTP_ACCEPT")
if user_agent and http_accept:
agent = mdetect.UAgentInfo(userAgent=user_agent, httpAccept=http_accept)
is_tablet = agent.detectTierTablet()
is_phone = agent.detectTierIphone()
is_mobile = is_tablet or is_phone or agent.detectMobileQuick()
request.is_mobile = is_mobile
request.is_tablet = is_tablet
request.is_phone = is_phone
最后,确保在您的设置文件中将'mobileesp.middleware.MobileDetectionMiddleware', 包含在MIDDLEWARE_CLASSES 中。
有了它,您可以在您的视图中(或任何您有请求对象的地方)检查is_phone(适用于任何现代智能手机)、is_tablet(适用于现代平板电脑)或is_mobile(适用于任何任何移动设备)。
【讨论】:
ios、android、windows phone吗?
detectIphoneOrIpod、detectAndroidPhone 或 detectWindowsPhone 等方法存储到请求对象的布尔变量中。评论很好,所以请确保您使用的正是您需要的检测方法。
看看MobileESP。它最近被移植到 Python for Django web 应用程序框架。它可以检测各种类别和层级的设备(包括智能手机、平板电脑)。
【讨论】:
如果您想要一些快速简单的解决方案,您可以尝试handset detection's javascript,它可以让您创建简单的重定向规则。
【讨论】:
from django_user_agents.utils import get_user_agent
def my_view(request):
user_agent = get_user_agent(request)
if user_agent.is_mobile:
# identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)
if user_agent.is_tablet:
# identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)
if user_agent.is_pc:
# identified to be running a traditional "desktop" OS (Windows, OS X, Linux)
它在底层使用user_agents。
【讨论】:
我一直在寻找类似的东西,但我偶然发现了 django-mobile,它正是这样做的。
【讨论】: