简体   繁体   中英

disable commit in Psycopg2

I want to run a few tests in inserting data to a postgresql-9.3 db, I am using Python-2.7 and the Psycopg2 api.

Up to now i was using it in alot of modules and doing commit() after some operations. since there are many commit() locations, i dont want to go and add an test_mode IF to all those commits, so what i thought would be best is to redirect the commit in a test_mode case to a void function:

#create connection
connection = psycopg2.connect(host=db_host, database=db_name, user=db_user, password=db_pwd,)

#in test_mode disable commit functionality
def void():
    print("No commit,this is a test mode")
if settings.test_mode:
    connection.commit=void

But what i get is this

AttributeError: 'psycopg2._psycopg.connection' object attribute 'commit' is read-only 

Any advice is welcome!

You can wrap the connection object with a Proxy class:

class FakeConnection(object):
    def __init__(self, connection):
        self.connection = connection
    def __getattr__(self, name):
        return getattr(self.connection, name)
    def __setattr__(self, name, value):
        if name != "connection": 
            setattr(self.connection, name, value)
        else:
            super(self, FakeConnection).__setattr__(name, value)
    def commit(self, *args, **kwargs):
        pass

Though it would be much better if you can avoid sprinkling your code with commit all over the place.

You can use ROLLBACK

if settings.test_mode:
    connection.rollback()
else:
    connection.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM