Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 605
Jesvin Jose Avatar asked Aug 08 '14 07:08

Jesvin Jose


People also ask

What does DB Drop_all () do?

You delete everything in the database using the db. drop_all() function to add the tags and post_tag tables safely and to avoid any of the common issues related to adding new tables to a database. Then you create all the tables anew using the db. create_all() function.

What is SQLAlchemy commit?

commit() commits (persists) those changes to the database. flush() is always called as part of a call to commit() (1). When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds.

Is SQLAlchemy engine thread safe?

Every pool implementation in SQLAlchemy is thread safe, including the default QueuePool . This means that 2 threads requesting a connection simultaneously will checkout 2 different connections. By extension, an engine will also be thread-safe.

Does SQLAlchemy close connection automatically?

connect() method returns a Connection object, and by using it in a Python context manager (e.g. the with: statement) the Connection. close() method is automatically invoked at the end of the block.


1 Answers

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})
like image 159
Andrew Magee Avatar answered Sep 29 '22 11:09

Andrew Magee