Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alchemy no transaction begun error

I run 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 transaction is begun.

the 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'>}

Any one know what I am doing wrong?

Thanks, CG

like image 400
Cory Gwin Avatar asked Mar 08 '12 18:03

Cory Gwin


1 Answers

Got similar error "No transaction is begun" when executing commit mentioned below lines of code:

    db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
    db_session.add(target)
    db_session.commit()

In my case, error occurred as I had autocommit set to True as well as tried to commit(). To resolve the issue had set autocommit to False as in code below.

db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

Thanks, Karthik

like image 199
Karthik Palaniappan Avatar answered Nov 07 '22 16:11

Karthik Palaniappan