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.
Advertisement
Answer
JavaScript
x
3
1
from flask import request
2
request.headers.get('User-Agent')
3
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
:
JavaScript
1
26
26
1
from ua_parser import user_agent_parser
2
from werkzeug.user_agent import UserAgent
3
from werkzeug.utils import cached_property
4
5
6
class ParsedUserAgent(UserAgent):
7
@cached_property
8
def _details(self):
9
return user_agent_parser.Parse(self.string)
10
11
@property
12
def platform(self):
13
return self._details['os']['family']
14
15
@property
16
def browser(self):
17
return self._details['user_agent']['family']
18
19
@property
20
def version(self):
21
return '.'.join(
22
part
23
for key in ('major', 'minor', 'patch')
24
if (part := self._details['user_agent'][key]) is not None
25
)
26