我需要检测3种类型的设备:tablet
,mobile
或desktop
。
我找到了一个用于检测移动on github的脚本,但如何检测移动、平板电脑和台式机?
发布于 2012-06-18 23:28:45
根据您以前使用过的移动检测中间件,我推荐以下几点:
选择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
最后,确保在设置文件中包含MIDDLEWARE_CLASSES
中的'mobileesp.middleware.MobileDetectionMiddleware',
。
有了这些,在你的视图中(或者你有一个请求对象的任何地方),你可以检查is_phone
(适用于任何现代智能手机),is_tablet
(适用于现代平板电脑)或is_mobile
(适用于任何移动设备)。
发布于 2012-03-07 12:04:09
看看MobileESP吧。它最近被移植到Django web应用框架的Python上。它可以检测各种类别和层次的设备(包括smatphones、平板电脑)。
发布于 2012-02-03 02:30:07
如果您想要一些快速而简单的解决方案,您可以尝试使用handset detection's javascript来创建简单的重定向规则。
https://stackoverflow.com/questions/9119594
复制