Random Number Range Generator with Validation

  • Share this:

Code introduction


This code defines a Pydantic model for generating a random number range. The model includes two fields: min_value and max_value, and uses the validator decorator to ensure that min_value is less than max_value. Then, the code assigns values to these fields using a random number generator and attempts to instantiate the model. If the assigned values do not meet the validation conditions, an error message will be returned.


Technology Stack : Pydantic

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from pydantic import BaseModel, ValidationError, validator
from random import randint
from typing import Optional

def generate_random_number_model():
    class RandomNumberModel(BaseModel):
        min_value: int
        max_value: int
        
        @validator('min_value', 'max_value')
        def validate_range(cls, value, values, **kwargs):
            if values['min_value'] >= values['max_value']:
                raise ValueError("min_value must be less than max_value")
            return value

    min_value = randint(1, 100)
    max_value = randint(min_value + 1, 100)
    try:
        model = RandomNumberModel(min_value=min_value, max_value=max_value)
        return model
    except ValidationError as e:
        return {"error": str(e)}                
              
Tags: