繁体   English   中英

禁用Psycopg2中的提交

[英]disable commit in Psycopg2

我想在将数据插入到postgresql-9.3 db中运行一些测试,我正在使用Python-2.7和Psycopg2 api。

到目前为止,我在很多模块中都使用它,并在进行一些操作后执行commit() 由于有很多commit()位置,所以我不想去给所有这些提交添加一个test_mode IF,所以我认为最好的方法是将test_mode情况下的提交重定向到void函数:

#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

但是我得到的是这个

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

欢迎任何建议!

您可以使用Proxy类包装连接对象:

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

如果可以避免在整个地方都花很多代码来提交代码,那会更好。

您可以使用ROLLBACK

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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