Search code examples
pythonhasattr

hasattrr to check properties of a object in python


I am writing web services using Python flask. I have created a class and loading its property names and values from user input (json data provided with service call).

from flask import json
class DataSetContract(object):
    """description of class"""

    def __init__(self, j):
        self.__dict__ = json.loads(j)

I am also getting a list of value property name as part of other input to my service.

unable to achieve... list of properties for example... {"from value","To Value","some values"}

property names have spaces in it.

I have another class where I am saving these property names

class FxConvertContract(object):
    """description of class"""

    def __init__(self, j):
        self.INPUT_CURRENCY = ""
        self.INPUT_AMOUNT = "" 
        self.RETURN_CURRENCY = ""
        self.RETURN_VALUE = ""
        self.ROUNDING = ""
        self.RETURN_RATE = ""
        self.__dict__ = json.loads(j)

now the goal is how can I verify if all the properties in list is populated properly and none of them is missing.

I tried 'in' and 'hasattr' method but nothing is working.

class DataSetValidator(object):

    def validate(self,dsList,convert):
        if(dsList == None or len(dsList) < 1):
            raise BadRequest("either Convert List or Data Set Source required.")

        for item in dsList:
            if(convert.INPUT_CURRENCY in item):
                raise BadRequest("INPUT_CURRENCY property not found.")
            if(hasattr(item,convert.INPUT_AMOUNT) == False):
                raise BadRequest("INPUT_AMOUNT property not found.")
            if(hasattr(item,convert.RETURN_CURRENCY) == False):
                raise BadRequest("RETURN_CURRENCY property not found.")
            if(hasattr(item,convert.RETURN_VALUE) == False):
                raise BadRequest("RETURN_VALUE property not found.")

        return True

Can anyone know how can I verify if data object contains all properties.

Thanks in advance...


Solution

  • Assuming this is what you're trying to do, hasattr will work:

    In [1]: from flask import json 
       ...: class DataSetContract(object): 
       ...:     """description of class""" 
       ...:  
       ...:     def __init__(self, j): 
       ...:         self.__dict__ = json.loads(j) 
       ...:                                                                                                                                                                 
    
    In [2]: class FxConvertContract(object): 
       ...:     """description of class""" 
       ...:  
       ...:     def __init__(self, j): 
       ...:         self.INPUT_CURRENCY = "" 
       ...:         self.INPUT_AMOUNT = ""  
       ...:         self.RETURN_CURRENCY = "" 
       ...:         self.RETURN_VALUE = "" 
       ...:         self.ROUNDING = "" 
       ...:         self.RETURN_RATE = "" 
       ...:         self.__dict__ = json.loads(j) 
       ...:                                                                                                                                                                 
    
    In [3]: class DataSetValidator(object): 
       ...:  
       ...:     def validate(self, dsList, convert): 
       ...:         if(dsList is None or len(dsList) < 1): 
       ...:             raise BadRequest("either Convert List or Data Set Source required.") 
       ...:  
       ...:         for item in dsList: 
       ...:             if(not hasattr(item, convert.INPUT_CURRENCY)): 
       ...:                 raise BadRequest("INPUT_CURRENCY property not found.") 
       ...:             if(not hasattr(item, convert.INPUT_AMOUNT)): 
       ...:                 raise BadRequest("INPUT_AMOUNT property not found.") 
       ...:             if(not hasattr(item, convert.RETURN_CURRENCY)): 
       ...:                 raise BadRequest("RETURN_CURRENCY property not found.") 
       ...:             if(not hasattr(item, convert.RETURN_VALUE)): 
       ...:                 raise BadRequest("RETURN_VALUE property not found.") 
       ...:  
       ...:         return True 
       ...:                                                                                                                                                                 
    
    In [4]: class BadRequest(Exception): pass                                                                                                                               
    
    In [7]: contract = FxConvertContract("""{ 
       ...:     "INPUT_CURRENCY": "in_currency", 
       ...:     "INPUT_AMOUNT": "in_amount", 
       ...:     "RETURN_CURRENCY": "re_currency", 
       ...:     "RETURN_VALUE": "re_value", 
       ...:     "ROUNDING": "rounding", 
       ...:     "RETURN_RATE": "re_rate" 
       ...: }""")                                                                                                                                                           
    
    In [8]: data = DataSetContract("""{ 
       ...:     "in_currency": "USD", 
       ...:     "in_amount": 1, 
       ...:     "re_currency": "CAD", 
       ...:     "re_value": 1.33, 
       ...:     "rounding": 0, 
       ...:     "re_rate": 1.33 
       ...: }""")                                                                                                                                                           
    
    In [9]: validator = DataSetValidator()                                                                                                                                  
    
    In [12]: validator.validate([data], contract)                                                                                                                            
    Out[12]: True