Skip to content

Best way to parse the user_agent property? #4228

Answered by tachyondecay
SuperSajuuk asked this question in Q&A
Discussion options

You must be logged in to vote

You don't need to subclass Request, but you do need to subclass werkzeug.user_agent.UserAgent. Then you can set app.request_class.user_agent_class to be your new user agent class, like so:

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()

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@SuperSajuuk
Comment options

Answer selected by SuperSajuuk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants