如何使用 Flask 获取用户代理? [英] How do I get the user agent with Flask?
问题描述
我正在尝试使用 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.
推荐答案
from flask import request
request.headers.get('User-Agent')
您也可以使用请求.user_agent
对象包含以下基于 useragent 字符串创建的属性:
You can also use the request.user_agent
object which contains the following attributes which are created based on the useragent string:
- 平台(windows、linux、macos 等)
- 浏览器(chrome、firefox、msie 等)
- 版本
- 语言
- string (
== request.headers.get('User-Agent')
)
注意:从werkzeug 2.0开始,request.user_agent
的解析数据已被弃用;如果您想继续获取详细信息,则需要使用自定义 UserAgent
实现并将其设置为自定义 Request
子类上的 user_agent_class
,该子类已设置作为 Flask
实例(或子类)上的 request_class
.
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).
这是一个使用 ua-parser
:
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
)
这篇关于如何使用 Flask 获取用户代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!