Best way to parse the user_agent property? #4228
-
Hi all, I'm looking to do some work with the user_agent property on a request object [I don't subclass Request, but use the default implementation]. I noticed in the documentation that this only contains a string property that must be parsed and online, I found a simple solution to parse that with a subclassed UserAgent. However, the example also suggested I needed to subclass Request to use that subclass. Does anyone know how I would use the default user_agent property without requiring the Request to be subclassed in order to use a custom parser for the user agent? Thank you! ❤ |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You don't need to subclass from flask import Flask, request
from werkzeug.user_agent import UserAgent
class NewUserAgent(UserAgent):
def new_method(self):
return f"Hello, world, here is your user agent: {self.string}"
app = Flask(__name__)
app.request_class.user_agent_class = NewUserAgent
@app.route("/")
def index():
return request.user_agent.new_method() |
Beta Was this translation helpful? Give feedback.
You don't need to subclass
Request
, but you do need to subclasswerkzeug.user_agent.UserAgent
. Then you can setapp.request_class.user_agent_class
to be your new user agent class, like so: