Parse HTTP_USER_AGENT string in django.

2019-02-16 19:22发布

What is a best way to parse User Agent string from the django request?

request.META.get('HTTP_USER_AGENT', '')

here is what i get in the string.

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36

Not sure how to parse this information.

Is there any cost(time, + memory) efficient solution. I just need to parse the string thats' all.

1条回答
聊天终结者
2楼-- · 2019-02-16 20:16

you can try this library :

https://pypi.python.org/pypi/user-agents/

Example :

from user_agents import parse

# iPhone's user agent string
ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'
user_agent = parse(ua_string)

# Accessing user agent's browser attributes
user_agent.browser  # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
user_agent.browser.family  # returns 'Mobile Safari'
user_agent.browser.version  # returns (5, 1)
user_agent.browser.version_string   # returns '5.1'

# Accessing user agent's operating system properties
user_agent.os  # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
user_agent.os.family  # returns 'iOS'
user_agent.os.version  # returns (5, 1)
user_agent.os.version_string  # returns '5.1'

# Accessing user agent's device properties
user_agent.device  # returns Device(family='iPhone')
user_agent.device.family  # returns 'iPhone'
查看更多
登录 后发表回答