Random User Data Generation with Sanic and Jinja2

  • Share this:

Code introduction


This function uses the Sanic web framework and the SanicJinja2 plugin to generate an HTML page containing random user data. It first generates a user data dictionary, then uses the Jinja2 template engine to render the data into an HTML page, and returns this page.


Technology Stack : Sanic, SanicJinja2, Jinja2

Code Type : Web API

Code Difficulty : Intermediate


                
                    
def random_user_data(request):
    import random
    from sanic import response
    from sanic_jinja2 import SanicJinja2

    jinja = SanicJinja2(request.app)

    # Generate a random user data
    user_data = {
        "id": random.randint(1, 1000),
        "name": "John Doe",
        "email": "john.doe@example.com",
        "age": random.randint(18, 65)
    }

    # Render the user data in a template
    rendered_template = jinja.render('user.html', user=user_data)

    return response.html(rendered_template)