Starlette Middleware for Random User-Agent Selection

  • Share this:

Code introduction


This function is a Starlette middleware that randomly selects a user agent string and sets it as the User-Agent in the response headers.


Technology Stack : Starlette

Code Type : Starlette Middleware

Code Difficulty : Intermediate


                
                    
def random_user_agent(response):
    import random
    import starlette.responses

    # List of user agents to choose from
    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 UBrowser/6.0 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
    ]

    # Choose a random user agent
    selected_user_agent = random.choice(user_agents)

    # Set the user agent in the response headers
    response.headers["User-Agent"] = selected_user_agent

    # Return the modified response
    return response                
              
Tags: