Python 在Psycopg2中禁用提交
我想在向postgresql-9.3 db插入数据时运行一些测试, 我正在使用Python-2.7和Psycopg2API 到目前为止,我在许多模块中使用它,并在一些操作之后执行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=
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()