禁用Psycopg2中的提交

2024-04-19 22:55:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在postgresql-9.3db中插入数据, 我使用的是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

但我得到的是这个

^{pr2}$

欢迎任何建议!在


Tags: 模块数据方法testhostdbmodepostgresql
2条回答

可以用代理类包装connection对象:

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()

相关问题 更多 >