def get_scalar(self, cursor, index=0): """Returns a single value from the first returned record from a cursor. By default it will get cursor.fecthone()[0] which works with tuples and namedtuples. For dict cursor it is necessary to specify index. This method will not work with cursors that aren't indexable. :param cursor: a cursor object :param index: the index of the cursor to return the value from """ if isinstance(index, int): return cursor.fetchone()[index] else: return get_value(cursor.fetchone(), index)
def test_get_value(self): class A(object): def __init__(self): self.n = 10 self.assertEqual(h.get_value(A(), "n"), 10) self.assertEqual(h.get_value(A(), "d"), None) self.assertEqual(h.get_value(dict(n=10), "n"), 10) self.assertEqual(h.get_value(dict(v=10), "n", "hi"), "hi") self.assertEqual(h.get_value(dict(v=10), "n", lambda: "lo"), "lo") self.assertEqual(h.get_value(None, "n", 42), 42)
def _initialize_attributes(self, data): """Initializes the class with the given data. Used by __init__.""" attrs = dict(self.attrs) if self.primary_key_name is None: pass elif isinstance(self.primary_key_name, str): if self.primary_key_name not in attrs: attrs[self.primary_key_name] = None else: for pkey in self.primary_key_name: if pkey not in attrs: attrs[pkey] = None if self.timestamps: for ts_name in self.timestamps: if ts_name is not None and ts_name not in attrs: attrs[ts_name] = None for attr_name in attrs: setattr(self, attr_name, get_value(data, attr_name, attrs[attr_name]))