def test_get_object_from_python_path(self): from aybu.core.utils import get_object_from_python_path from aybu.core.models import Node from aybu.core.models import NodeInfo self.assertRaises(ValueError, get_object_from_python_path, None) self.assertRaises(ValueError, get_object_from_python_path, '') self.assertRaises(ValueError, get_object_from_python_path, 'wrong_name') path = 'aybu.core.models.Node' self.assertEqual(Node, get_object_from_python_path(path)) path = 'aybu.core.models.NodeInfo' self.assertEqual(NodeInfo, get_object_from_python_path(path)) path = 'aybu.core.models.wrong_name' self.assertRaises(ValueError, get_object_from_python_path, path)
def add_default_data(session, data): seq_classes = {} for params in data: cls = 'aybu.core.models.%s' % params.pop('cls_') cls = get_object_from_python_path(cls) mapper = class_mapper(cls) if hasattr(cls, "id_seq") and not cls.__name__ in seq_classes: seq_classes[cls.__name__] = cls for key, value in params.iteritems(): if not value is None: try: property_ = mapper.get_property(key) except: continue if not hasattr(property_, 'argument'): continue try: class_ = property_.argument.class_ except AttributeError: class_ = property_.argument() query = session.query(class_) if not property_.uselist and len(mapper.primary_key) == 1: params[key] = query.get(value) continue obj = cls(**params) obj = session.merge(obj) for cls in seq_classes.values(): """ This works (and is needed) only on postrgresql to fix autoincrement """ tablename = cls.__tablename__ log.debug("Fixing sequence for cls %s (%s)", cls, tablename) seqname = "{}_id_seq".format(tablename) try: session.execute( "SELECT setval('{}', max(id)) FROM {};".format(seqname, tablename) ) except sqlalchemy.exc.OperationalError: # raised by MySQLdb pass except sqlalchemy.exc.ProgrammingError: # raised by oursql pass