def clone(self, source): for column in source.__table__.c: if column.name != 'id': setattr(self, camelcase_to_underscore(column.name), getattr( source, camelcase_to_underscore(column.name))) else: setattr(self, 'id', uuid())
def clone(self, source): for column in source.__table__.c: if column.name != 'id': setattr(self, camelcase_to_underscore(column.name), getattr(source, camelcase_to_underscore(column.name))) else: setattr(self, 'id', uuid())
def from_dict(self, the_dict, strict=False): ''' Convenience method to populate a model from a dict. It will automatically convert camel case keys to underscore equivalents. @param: the_dict: A dictionary of values to be set in the model. @param: strict: A boolean switch to throw an exception if the corresponding key is not found @return: An instance of the model with the keys set. ''' for key in the_dict: us_key = camelcase_to_underscore(key) if hasattr(self, us_key): setattr(self, us_key, the_dict[key]) else: if strict: raise UserWarning('from_dict() error: The %s model does not have a %s key.' % ( self.__class__, us_key)) return self
def from_dict(self, the_dict, strict=False): ''' Convenience method to populate a model from a dict. It will automatically convert camel case keys to underscore equivalents. @param: the_dict: A dictionary of values to be set in the model. @param: strict: A boolean switch to throw an exception if the corresponding key is not found @return: An instance of the model with the keys set. ''' for key in the_dict: us_key = camelcase_to_underscore(key) if hasattr(self, us_key): setattr(self, us_key, the_dict[key]) else: if strict: raise UserWarning( 'from_dict() error: The %s model does not have a %s key.' % (self.__class__, us_key)) return self
def to_dict(self, camel_case=False, columns=None, datetime_to_str=False): ''' Convenience method to generate a dict from a model instance. It can automatically convert camel case keys to underscore equivalents. @param: camel_case: A boolean switch to convert the resulting dict keys to camel case. @param: columns: A list of (camelCased) columns that should be included in the result as keys. @return: An dict with all the columns of the model as keys and values. ''' return_dict = {} for column in self.__table__.c: us_column_name = camelcase_to_underscore(column.name) if not columns or column.name in columns: if camel_case: key = column.name else: key = us_column_name value = str(getattr(self, us_column_name)) if datetime_to_str: if isinstance(value, datetime): value = str(value) return_dict[key] = value return return_dict