Random User Data Generator with Sanic and Jinja2

  • Share this:

Code introduction


This code defines a web API based on the Sanic framework that generates random user data. User data includes name, email, and age, which are rendered on a webpage using Jinja2 templates.


Technology Stack : Sanic, Jinja2

Code Type : Web API

Code Difficulty : Intermediate


                
                    
def random_user_data(user_id):
    import random
    from sanic import Sanic, response
    from sanic_jinja2 import SanicJinja2

    app = Sanic(__name__)
    jinja = SanicJinja2(app)

    @app.route("/random-user/<int:user_id>")
    async def random_user(request, user_id):
        # Generate a random user data
        user_data = {
            "name": f"User{random.randint(1, 1000)}",
            "email": f"user{random.randint(1, 1000)}@example.com",
            "age": random.randint(18, 70)
        }
        return jinja.render("user.html", request, user=user_data)

    return app                
              
Tags: