Jesvin Jose
Jesvin Jose

Reputation: 23088

Autocommit in Flask-SQLAlchemy

How do I set initilize my Flask application to set Flask-SQLAlchemy to autocommit mode, to not use transactions unless I explicitly session.begin()?

The session "begins a database transaction as soon as it starts communicating". Does this affect Postgres harder than MySQL?


By Instagram,

autocommit mode; in this mode, Psycopg2 won’t issue BEGIN/COMMIT for any queries; instead, every query runs in its own single-statement transaction. This is particularly useful for read-only queries where transaction semantics aren’t needed. It’s as easy as doing:

connection.autocommit = True

This lowered chatter between our application servers and DBs significantly, and lowered system CPU as well on the database boxes

Upvotes: 12

Views: 15025

Answers (2)

Andrew Magee
Andrew Magee

Reputation: 6684

I think you can set autocommit in Flask-SQLAlchemy doing this:

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(session_options={'autocommit': True})

Edit: the 'flask.ext.' form is now depricated (see here)

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(session_options={'autocommit': True})

Upvotes: 21

codegeek
codegeek

Reputation: 33309

Since you are using Flask-SQLAlchemy, it has autocommit = False by default. See this code here

It does say that if you want to turn on autocommit to True by default, you will have to override the SQLAlchemy.create_session function.

Upvotes: 2

Related Questions