Asynchronous Random User Data Generator Using Sanic

  • Share this:

Code introduction


This code defines an asynchronous HTTP service based on the Sanic framework, used to generate random user data. The user data includes user ID, name, and email address.


Technology Stack : Sanic, Python built-in modules (random, string)

Code Type : Asynchronous HTTP service

Code Difficulty : Intermediate


                
                    
def random_user_data(user_id):
    from sanic import Sanic
    from sanic.response import json
    import random
    import string

    app = Sanic()

    @app.route('/random_user/<int:user_id>')
    async def get_random_user_data(request, user_id):
        # Generate a random user data
        user_data = {
            "id": user_id,
            "name": ''.join(random.choices(string.ascii_uppercase, k=5)),
            "email": f"{random.choice(string.ascii_uppercase)}{random.randint(1000, 9999)}@example.com"
        }
        return json(user_data)

    return app