How do I get the user agent with Flask?

I'm trying to get access to the user agent with Flask, but I either can't find the documentation on it, or it doesn't tell me.


Solution 1:

from flask import request
request.headers.get('User-Agent')

You can also use the request.user_agent object which contains the following attributes which are created based on the useragent string:

  • platform (windows, linux, macos, etc.)
  • browser (chrome, firefox, msie, etc.)
  • version
  • language
  • string (== request.headers.get('User-Agent'))

Note: As of werkzeug 2.0, the parsed data of request.user_agent has been deprecated; if you want to keep getting details you need to use a custom UserAgent implementation and set it as user_agent_class on a custom Request subclass, which is set as request_class on the Flask instance (or a subclass).

Here's an example implementation that uses ua-parser:

from ua_parser import user_agent_parser
from werkzeug.user_agent import UserAgent
from werkzeug.utils import cached_property


class ParsedUserAgent(UserAgent):
    @cached_property
    def _details(self):
        return user_agent_parser.Parse(self.string)

    @property
    def platform(self):
        return self._details['os']['family']

    @property
    def browser(self):
        return self._details['user_agent']['family']

    @property
    def version(self):
        return '.'.join(
            part
            for key in ('major', 'minor', 'patch')
            if (part := self._details['user_agent'][key]) is not None
        )

Solution 2:

If you use

request.headers.get('User-Agent')

you may get: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36

If you use

request.user_agent

you may get like this:

  • user_agent.platform: windows
  • user_agent.browser: chrome
  • user_agent.version: 45.0.2454.101
  • user_agent.language: None
  • user_agent.string: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36