Random User Model Generation with Pydantic

  • Share this:

Code introduction


This code defines a function named random_string that generates a random string of a specified length using Python's random and string libraries. It then defines a User class that inherits from pydantic's BaseModel and adds three fields: username, age, and email. Finally, it defines a function generate_user_model that randomly selects a field, and if it's the phone field, it dynamically adds a phone field to the User class.


Technology Stack : Python, Pydantic, random, string

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
from pydantic import BaseModel, Field
from random import choice
import string

def random_string(length: int = 10):
    """Generate a random string of fixed length."""
    letters = string.ascii_letters + string.digits
    return ''.join(choice(letters) for i in range(length))

class User(BaseModel):
    username: str = Field(..., description="The username of the user")
    age: int = Field(..., ge=0, le=120, description="The age of the user")
    email: str = Field(..., description="The email address of the user")

def generate_user_model():
    """Generate a Pydantic user model with random fields."""
    fields = [
        ('username', 'str'),
        ('age', 'int'),
        ('email', 'str'),
        ('phone', 'str')
    ]
    random_fields = choice(fields)
    if random_fields[0] == 'phone':
        phone_field = Field(..., description="The phone number of the user")
        User = type('User', (BaseModel,), {'phone': phone_field})
    else:
        User = User
    return User

# Generate a random user model
RandomUserModel = generate_user_model()