Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

How to change autocommit in SQLAlchemy in the middle of the application

I have a webapp that communicates with a postgres database via SQLAlchemy. The default value of autocommit=False is good for the most part of the application. With autocommit=False, the following code runs ok.

db = sqlalchemy(session_options={'autocommit': False})
...
def func1():
    db.session.add(image1)
    db.session.commit()

def func2():
    db.session.add(image2)
    db.session.commit()

def func3():
    db.session.add(image3)
    db.session.commit()

    db.session.add(image4)
    db.session.commit()

I now, want to use single commit for multiple inserts/update operations.
I can change my db session to autocommit=True, and call db.session.begin() before every operation, e.g.

db = SQLAlchemy(session_options={'autocommit': True})
...
def func1():
    db.session.begin()
    db.session.add(image1)
    db.session.commit()

def func2():
    db.session.begin()
    db.session.add(image2)
    db.session.commit()

def func3():
    db.session.begin()
    db.session.add(image3)

    db.session.add(image4)
    db.session.commit()

But if I change back to autocommit = True, I get an error, that complains about the db.session.begin()

...
  File "/usr/src/app/web/app/api/sites.py", line 559, in view_sites
    db.session.begin()
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 949, in begin
    raise sa_exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: A transaction is already begun.  Use subtransactions=True to allow subtransactions.
...

According to here subtransactions will become obsolete in future versions of sqlalchemy ?

I'm looking for a way to programatically set autocommit=True in the beginning of func3, and turn it back to autocommit=True in the end of func3
Is this possible?

Thanks

question from:https://stackoverflow.com/questions/65910920/how-to-change-autocommit-in-sqlalchemy-in-the-middle-of-the-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...