Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Psycopg2中禁用提交_Python_Postgresql_Psycopg2 - Fatal编程技术网

Python 在Psycopg2中禁用提交

Python 在Psycopg2中禁用提交,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我想在向postgresql-9.3 db插入数据时运行一些测试, 我正在使用Python-2.7和Psycopg2API 到目前为止,我在许多模块中使用它,并在一些操作之后执行commit()。 由于有许多commit()位置,我不想在所有这些提交中添加测试模式, 因此,我认为最好是在测试模式下将提交重定向到void函数: #create connection connection = psycopg2.connect(host=db_host, database=db_name, user=

我想在向postgresql-9.3 db插入数据时运行一些测试, 我正在使用Python-2.7和Psycopg2API

到目前为止,我在许多模块中使用它,并在一些操作之后执行
commit()
。 由于有许多
commit()
位置,我不想在所有这些提交中添加测试模式, 因此,我认为最好是在测试模式下将提交重定向到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 

欢迎任何意见

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

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

不过,如果您可以避免在代码中到处使用commit,那就更好了。

您可以使用
回滚

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