You can download this code by clicking the button below.
This code is now available for download.
This function fetches a list of user agents from a public API, randomly selects one from the list, and adds it to the HTTP response headers.
Technology Stack : Sanic, requests, random
Code Type : HTTP Response
Code Difficulty : Intermediate
def random_user_agent(response):
import random
import requests
from sanic import response as sanic_response
# Fetch a list of user agents from a public API
response = requests.get("https://api.useragents.org/")
user_agents = response.json()
# Randomly select a user agent from the list
selected_user_agent = random.choice(user_agents["user_agents"])
# Add the user agent to the response headers
return sanic_response.text(f"Selected User Agent: {selected_user_agent}", headers={"User-Agent": selected_user_agent})