Random User Information Handler in Falcon Framework

  • Share this:

Code introduction


This function is a handler in the Falcon web framework that returns information about a randomly selected user. It first defines a list of users, then randomly selects one user from it, and finally returns this user's information in JSON format.


Technology Stack : This function is a handler in the Falcon web framework that returns information about a randomly selected user. It first defines a list of users, then randomly selects one user from it, and finally returns this user's information in JSON format.

Code Type : Web framework

Code Difficulty : Intermediate


                
                    
import falcon
import random

def random_user_handler(req, resp):
    # Generate a random user dictionary
    users = [
        {"id": 1, "name": "Alice", "age": 25},
        {"id": 2, "name": "Bob", "age": 30},
        {"id": 3, "name": "Charlie", "age": 35},
        {"id": 4, "name": "David", "age": 40}
    ]
    random_user = random.choice(users)
    
    # Set the response content type and body
    resp.status = falcon.HTTP_200
    resp.content_type = 'application/json'
    resp.body = json.dumps(random_user)