SQL Alchemy not started transaction error

I am running the following code

db = create_engine('sqlite:///tracking_test.db')
db.echo= True
metadata = MetaData(db)
session = create_session(bind=db)
#define tables, if they exist sqlalchemly will find them and sycn otherwise they will be created
delivered= Table('delivered', metadata,
    Column('delivered_id',Integer,primary_key=True),
    Column('domain',String(200)),
    Column('path',String(500)),
    )

class Delivered(object):        
    def __init__(self,obj):
        self.domain=u'%s' % obj.get("dm","")
        self.path=u'%s' % obj.get("pth","")


report1t = Table('clicked', metadata,
    Column('clicked_id',Integer,primary_key=True),
    Column('domain',String(200)),
    Column('path',String(500)),

)

class report1(object):
    def __init__(self,obj):
        self.domain=u'%s' % obj.get("dm","")
        self.path=u'%s' % obj.get("pth","")


metadata.create_all()
mapper(report1, report1t)
mapper(Delivered,delivered)
result= {}#some dict
newT = Delivered(result)
if newT:
    session.add(newT)
    session.commit()
    session.flush()

      

And I get this error sqlalchemy.exc.InvalidRequestError: No transactions started.

session dict say:

{'autocommit': True, 'autoflush': False, 'transaction': None, 'hash_key': 4317750544, 'expire_on_commit': False, '_new': {<sqlalchemy.orm.state.InstanceState object at 0x101a79ad0>: <__main__.adDelivered object at 0x101a799d0>}, 'bind': Engine(sqlite:///adtracking_test.db), '_deleted': {}, '_flushing': False, 'identity_map': {}, 'dispatch': <sqlalchemy.event.SessionEventsDispatch object at 0x101a82f90>, '_enable_transaction_accounting': True, '_identity_cls': <class 'sqlalchemy.orm.identity.WeakInstanceDict'>, 'twophase': False, '_Session__binds': {}, '_query_cls': <class 'sqlalchemy.orm.query.Query'>}

      

Does anyone know what I am doing wrong?

Thanks, CG

+3


source to share


1 answer


It would be helpful if you could post the complete alignment. However, I think the problem is with how you create the session. I think you should be using sessionmaker

, not create_session

(I've never seen this function before, and I don't see it documented anywhere). sessionmaker

creates a new class Session

to be created. So:



Session = sessionmaker(bind=db)
session = Session()
...
session.add(newT)

      

+5


source







All Articles