Random User Selection Web Server

  • Share this:

Code introduction


This function creates a simple web server that randomly selects a user from a given list of users and returns information about that user.


Technology Stack : Aiohttp-web, Python

Code Type : Web Server

Code Difficulty : Intermediate


                
                    
def get_random_user(arg1, arg2):
    from aiohttp import web
    import random

    async def get_user(request):
        users = arg1
        user_id = arg2
        user = random.choice(users)
        return web.Response(text=f"User: {user['name']}")

    app = web.Application()
    app.router.add_get('/user', get_user)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start()
    print("Server started at http://localhost:8080")