Last active
          October 18, 2025 07:05 
        
      - 
      
 - 
        
Save roganjoshp/5fe1aa1762495ede60ada10ce2c780ec to your computer and use it in GitHub Desktop.  
    Data Validation
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # SETUP IN utils.py | |
| class NumParse(Enum): | |
| VAL = 1 # Valid number | |
| INV = 2 # Invalid number format | |
| NEG = 3 # Negative value | |
| ZER = 4 # Zero value | |
| EXC = 5 # Exceeds maximum value defined in config | |
| def __eq__(self, other: str): | |
| return self.name == other | |
| def val_float( | |
| val: Any, nn: bool = True, nz: bool = False, ignore_max: bool = False | |
| ) -> tuple[NumParse, float | None]: | |
| """Helper function to validate user input is a float | |
| This is literally just to remove repetitive try/except blocks being | |
| repeated over and over when validating user input forms. It can additionally | |
| refuse negative numbers, and a ceiling on values is created in the App | |
| Config to prevent excessively large values. | |
| Parameters | |
| ---------- | |
| val : Any | |
| The value to be tested | |
| nn : bool | |
| Stands for non-negative. If True, negative values will be considered | |
| invalid | |
| nz : bool | |
| Stands for non-zero. If True, zero values will be considered invalid | |
| ignore_max : bool | |
| Whether to ignore the config-defined maximum value | |
| Returns | |
| ------- | |
| tuple[NumParse, float | None] | |
| An enum of the parsing outcome and, if successful, the parsed value | |
| """ | |
| try: | |
| val = float(val) | |
| except (TypeError, ValueError, OverflowError): | |
| return NumParse(2), None | |
| if val < 0 and nn: | |
| return NumParse(3), None | |
| elif val == 0 and nz: | |
| return NumParse(4), None | |
| if not ignore_max: | |
| if abs(val) > current_app.config["MAX_NUMBER"]: | |
| return NumParse(5), None | |
| return NumParse(1), val | |
| # APPLICATION | |
| from utils import NumpParse as NP | |
| from utils import val_float | |
| v, qty = val_float(qty, nz=True) # qty here is from the frontend | |
| if v is not NP.VAL: | |
| match v: | |
| case NP.INV: | |
| return False, _("Quantity not recognised") | |
| case NP.NEG | NP.ZER: | |
| return False, _("Quantity must be positive") | |
| case NP.EXC: | |
| return False, _("Maximum quantity exceeded") | |
| case z: # noqa: F841 | |
| return False, _("Unknown error occurred") | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment