[英]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. 我想在将数据插入到postgresql-9.3 db中运行一些测试,我正在使用Python-2.7和Psycopg2 api。
Up to now i was using it in alot of modules and doing commit()
after some operations. 到目前为止,我在很多模块中都使用它,并在进行一些操作后执行
commit()
。 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: 由于有很多
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
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: 您可以使用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
Though it would be much better if you can avoid sprinkling your code with commit all over the place. 如果可以避免在整个地方都花很多代码来提交代码,那会更好。
You can use ROLLBACK
您可以使用
ROLLBACK
if settings.test_mode:
connection.rollback()
else:
connection.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.