How to use READ ONLY transaction mode in SQLAlchemy?

In transaction access mode, PostgreSQL can be changed to READ ONLY( docs ). In SQLAlchemy, the isolation level can be changed for the engine, but the parameter is not available for read-only access mode ( docs ).

How to make an engine with READ ONLYconnection access mode?

+4
source share
1 answer

One solution is to execute an instruction for each transaction:

engine = create_engine('postgresql+psycopg2://postgres:pass@127.0.0.1:5432/')
@event.listens_for(engine, 'begin')
def receive_begin(conn):
    conn.execute('SET TRANSACTION READ ONLY')

But it is better to set the mode in the line BEGIN TRANSACTIONnot as a separate operator.

0
source

All Articles