在Django上检测手机,平板电脑或桌面

mac*_*era 19 django mobile

Im Junior djangodev.

我需要检测3种类型device,tablet,mobiledesktop.

我在github上找到了检测到的移动设备的脚本,但我如何检测移动设备,平板电脑和桌面?

谢谢!

Ada*_*tak 33

根据您之前使用的移动检测中间件,我建议如下:

拿起MobileESPPython端口(这里是源代码)(感谢Mariusz Miesiak的推荐)并将其放入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
Run Code Online (Sandbox Code Playgroud)

最后,请一定要包括'mobileesp.middleware.MobileDetectionMiddleware',MIDDLEWARE_CLASSES你的设置文件.

有了它,在您的视图中(或任何您有请求对象的地方),您可以检查is_phone(对于任何现代智能手机),is_tablet(对于现代平板电脑)或is_mobile(对于任何移动设备).

  • @andi - 是的,你可以用它来区分; 看看mdetect python代码,有一些方法,比如`detectIphoneOrIpod`,`detectAndroidPhone`或`detectWindowsPhone`,你可以将它们存储到请求对象的布尔变量中.评论很好,所以请确保您使用的是所需的检测方法. (2认同)

Mar*_*iak 5

看看MobileESP.它最近被移植到Python for Django Web应用程序框架.它可以检测各种类别和设备层(包括smatphones,平板电脑).


小智 1

如果您想要一些快速且简单的解决方案,您可以尝试手机检测的javascript,它使您能够创建简单的重定向规则。