Browser Detection Python / mod_python?

岁酱吖の 提交于 2020-01-14 10:44:09

问题


I want to keep some statistics about users and locations in a database. For instance, I would like to store "Mozilla","Firefox","Safari","Chrome","IE", etc... as well as the versions, and possibly the operating system.

What I am trying to locate from Python is this string;

Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.14) Gecko/2009090216 Ubuntu/9.04 (jaunty) Firefox/3.0.14

Is there an efficient way to use Python or mod_python to detect the http user agent/browser?


回答1:


HTTP_USER_AGENT contains this information, and will be passed in the environment variables your application uses. In mod_python, this is expressed as:

def my_request_handler(req):
    req.add_common_vars()
    agent = req.subprocess_env.get("HTTP_USER_AGENT")

    # `agent` now contains the full user agent of the browser, or None

It's a basic CGI thing, but this is how mod_python gives it to you.




回答2:


The method suggested by Jed Smith works, but I was sure there was a simpler way.

The req.headers_in variable contains all the header info, and you can easily access the user agent using mod_python by calling:

req.headers_in[ 'User-Agent' ]

It is not necessary to call req.add_common_vars() when using this method.




回答3:


If you are using the Django-Framework you get the user agent like this

request.META['HTTP_USER_AGENT']

The very nice plugin httpagentparser extracts every detail and puts it a dictionary.

Installation works via pip

pip install httpagentparser

Hope this helps... I googled about 30 min until I found something useful :)

Ron



来源:https://stackoverflow.com/questions/1689861/browser-detection-python-mod-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!