How to filter Flask application's requests based on user agents?

Jul 22, 2025Leave a message

Hey there! If you're running a Flask application, you might've come across the need to filter requests based on user agents. User agents are strings that identify the browser, device, or application making the request to your server. Filtering based on user agents can be super useful for various reasons, like blocking malicious bots, serving different content to specific browsers, or simply managing traffic.

As a Filtering Flask supplier, I've seen firsthand how important it is to have effective user - agent filtering in Flask applications. Let's dive into how you can achieve this.

Why Filter Based on User Agents?

First off, let's talk about why you'd want to filter requests based on user agents. Malicious bots are a big headache for web applications. They can overload your server, scrape your data, or perform other unwanted actions. By filtering out known bot user agents, you can protect your application from these threats.

Another reason is to serve different content based on the browser or device. For example, some older browsers might not support modern web technologies. You can detect these browsers through their user agents and serve them a simplified version of your application.

How to Get the User Agent in Flask

Before you can filter requests, you need to get the user agent from the incoming request. In Flask, it's pretty straightforward. You can use the request object, which is available in every route function. Here's a simple example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    user_agent = request.headers.get('User-Agent')
    return f'Your user agent is: {user_agent}'

if __name__ == '__main__':
    app.run(debug=True)

In this code, we're getting the User - Agent header from the request headers. The request.headers is a dictionary - like object that contains all the headers sent with the request.

Basic User - Agent Filtering

Now that we can get the user agent, let's start filtering. One simple way is to check if the user agent contains certain keywords. For example, if you want to block all requests from a specific bot, you can do something like this:

from flask import Flask, request, abort

app = Flask(__name__)

BLOCKED_USER_AGENTS = ['BadBot/1.0']

@app.route('/')
def index():
    user_agent = request.headers.get('User-Agent')
    if user_agent and any(bad_agent in user_agent for bad_agent in BLOCKED_USER_AGENTS):
        abort(403)
    return 'Welcome to my Flask app!'

if __name__ == '__main__':
    app.run(debug=True)

In this code, we have a list of blocked user agents. We check if the incoming user agent contains any of the blocked agents. If it does, we use the abort function to return a 403 Forbidden status code.

Using Regular Expressions for More Advanced Filtering

Sometimes, you need more flexibility in your filtering. That's where regular expressions come in handy. Regular expressions allow you to match patterns in strings. For example, if you want to block all bots that start with "Bot", you can use a regular expression.

import re
from flask import Flask, request, abort

app = Flask(__name__)

BOT_REGEX = re.compile(r'^Bot.*')

@app.route('/')
def index():
    user_agent = request.headers.get('User-Agent')
    if user_agent and BOT_REGEX.match(user_agent):
        abort(403)
    return 'Welcome to my Flask app!'

if __name__ == '__main__':
    app.run(debug=True)

Here, we're using the re module in Python to create a regular expression pattern. The ^ symbol means the pattern should start with "Bot", and the .* means it can be followed by any characters.

Filtering Based on Browser or Device

You might also want to serve different content based on the browser or device. For example, if it's a mobile device, you can serve a mobile - friendly version of your app. You can use libraries like ua - parser to parse the user agent and get more detailed information.

First, install the ua - parser library using pip install ua - parser. Then, here's how you can use it:

from flask import Flask, request
from ua_parser import user_agent_parser

app = Flask(__name__)

@app.route('/')
def index():
    user_agent = request.headers.get('User-Agent')
    if user_agent:
        parsed_ua = user_agent_parser.Parse(user_agent)
        device_type = parsed_ua['device']['family']
        if device_type in ['iPhone', 'iPad']:
            return 'Welcome on your Apple device!'
        else:
            return 'Welcome on other devices!'
    return 'Welcome!'

if __name__ == '__main__':
    app.run(debug=True)

In this code, we're using the ua - parser library to parse the user agent. We then check the device family. If it's an iPhone or iPad, we serve a specific message; otherwise, we serve a different message.

Clear glass Filtering FlaskLaboratory Filtering Flask

Some Useful Filtering Flasks for Your Lab

If you're in a laboratory setting, we also offer some great filtering flasks. Check out our Laboratory Clear Glass Filtering Flasks with Upper Tubulature and Laboratory Glass Conical Shape Erlenmeyer Filtering Flasks with Upper Tubulation. These flasks are designed to meet your filtering needs in a scientific environment.

Contact Us for Your Filtering Needs

Whether you're looking for Flask application user - agent filtering solutions or high - quality laboratory filtering flasks, we're here to help. If you're interested in purchasing our products or discussing your specific requirements, don't hesitate to reach out. We have a team of experts ready to assist you in finding the best solutions for your needs.

References

  • Flask Documentation.
  • Python re module documentation.
  • ua - parser library documentation.