You can download this code by clicking the button below.
This code is now available for download.
This function uses the Sanic web framework and Jinja2 template engine to generate a random user agent string and render it into an HTML template. It randomly selects one from the predefined list of user agents and passes the selected user agent to the HTML template through Jinja2.
Technology Stack : Sanic, Jinja2, HTML
Code Type : Web Application Function
Code Difficulty : Intermediate
def random_user_agent(request):
import random
from sanic import response
from sanic_jinja2 import SanicJinja2
jinja = SanicJinja2(request.app)
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 (Linux; Android 10; SM-A505FN) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Mobile Safari/537.36"
]
selected_user_agent = random.choice(user_agents)
return jinja.render(request, "user_agent.html", user_agent=selected_user_agent)