You can download this code by clicking the button below.
This code is now available for download.
This code creates a simple web application based on the Sanic framework and uses the Jinja2 template engine to randomly render different pages.
Technology Stack : Sanic, Jinja2, Sanic-Jinja2
Code Type : Web Application
Code Difficulty : Intermediate
import random
import sanic
import sanic_jinja2
def random_sanic_route():
# Define a simple Sanic app with a random Jinja2 template
app = sanic.Sanic(__name__)
app.config['JINJA2_ENV autoescape'] = True
app.config['JINJA2_ENV trim_blocks'] = True
app.config['JINJA2_ENV lstrip_blocks'] = True
sanic_jinja2.init(app, loader=sanic_jinja2.FileSystemLoader('./templates'))
@app.route("/")
async def index(request):
# Randomly choose a template to render
templates = ['home.html', 'about.html', 'contact.html']
template = random.choice(templates)
return await app.send_file(template, inline=True)
return app