在Django上检测手机,平板电脑或桌面 [英] Detect mobile, tablet or Desktop on Django
问题描述
Im Junior django dev。我需要检测到3种类型的设备,平板电脑,移动设备或桌面设备。我发现检测到的手机的脚本(https://github.com/macgera/macgera/blob/master/middleware.py),但我如何检测手机,平板电脑和桌面?
Im Junior django dev. I need detected 3 types of device, tablet, mobile, or desktop. I find script for detected mobile(https://github.com/macgera/macgera/blob/master/middleware.py), but how i can detect mobile, Tablet and desktop?
谢谢!
推荐答案
根据您以前使用的手机检测中间件,我建议以下内容:
Based on your prior use of mobile detection middleware, I'd recommend the following:
拿起 MobileESP的Python端口 (来源这里的代码)(感谢 Mariusz Miesiak 的推荐),并将其放入名为 mobileesp
在项目的基础(其中 manage.py
是)。抛出一个空白的 __ init __。py
文件,以便Python将其视为一个包。
Pick up the Python port of MobileESP (source code here) (thanks to Mariusz Miesiak for the recommendation) and drop it into a folder named mobileesp
in the base of your project (where manage.py
is). Throw in a blank __init__.py
file so that Python will see it as a package.
继续创建在该目录中的新文件 middleware.py
,并填写:
Go ahead and create a new file, middleware.py
, in that directory, and fill it with:
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',
code>在您的设置文件。
Lastly, make sure to include 'mobileesp.middleware.MobileDetectionMiddleware',
in MIDDLEWARE_CLASSES
in your settings file.
有了这一点,在您的视图(或任何您有请求对象的任何地方),您可以检查 is_phone
(适用于任何现代智能手机), is_tablet
(用于现代平板电脑)或 is_mobile
(任何移动设备)。
With that in place, in your views (or anywhere that you have a request object) you can check for is_phone
(for any modern smartphones), is_tablet
(for modern tablets) or is_mobile
(for any mobile devices whatsoever).
这篇关于在Django上检测手机,平板电脑或桌面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!