Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse HTTP_USER_AGENT string in django.

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.

like image 252
A.J. Avatar asked Mar 13 '14 10:03

A.J.


1 Answers

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'
like image 174
Priyank Patel Avatar answered Oct 17 '22 12:10

Priyank Patel