我如何检测客户端使用的浏览器类型。我有一个问题,我必须要求人们使用其他浏览器(Firefox)而不是IE。我如何获得此信息。
我知道http请求具有此信息(标头)。我如何从Django框架中的view.py获取navigator.appName?
Answers:
您可以像这样从请求对象中提取该信息:
request.META['HTTP_USER_AGENT']
有多种方法可以完成该任务。
最简单的方法是@digitaldreamer推荐的方法。也就是说,您可以请求HTTP_USER_AGENT
。
request.META['HTTP_USER_AGENT']
但是我也建议您看一下Django User Agents库。
用pip安装
pip install pyyaml ua-parser user-agents
pip install django-user-agents
并配置settings.py
:
MIDDLEWARE_CLASSES = (
# other middlewares...
'django_user_agents.middleware.UserAgentMiddleware',
)
INSTALLED_APPS = (
# Other apps...
'django_user_agents',
)
# Cache backend is optional, but recommended to speed up user agent parsing
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
# Name of cache backend to cache user agents. If it not specified default
# cache alias will be used. Set to `None` to disable caching.
USER_AGENTS_CACHE = 'default'
用法也很简单。
user_agent
现在将向请求添加一个属性,您可以在views.py中使用该属性:
def my_view(要求):
# Let's assume that the visitor uses an iPhone...
request.user_agent.is_mobile # returns True
request.user_agent.is_tablet # returns False
request.user_agent.is_touch_capable # returns True
request.user_agent.is_pc # returns False
request.user_agent.is_bot # returns False
# Accessing user agent's browser attributes
request.user_agent.browser # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
request.user_agent.browser.family # returns 'Mobile Safari'
request.user_agent.browser.version # returns (5, 1)
request.user_agent.browser.version_string # returns '5.1'
# Operating System properties
request.user_agent.os # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
request.user_agent.os.family # returns 'iOS'
request.user_agent.os.version # returns (5, 1)
request.user_agent.os.version_string # returns '5.1'
# Device properties
request.user_agent.device # returns Device(family='iPhone')
request.user_agent.device.family # returns 'iPhone'
您可以查看“用户代理字符串”并解析出值。
以下是相关文档,特别是(HTTP_USER_AGENT
):
http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36