构建一个类来使用`with`来建立独占的sql连接

时间:2015-01-06 04:32:26

标签: python with-statement

我正在开发一个简单的便捷类,与with运算符一起使用,这样我就可以为并发系统中的扩展写入会话建立对sqlite3数据库的独占访问权。

这是班级:

import sqlite3 as sql

class ExclusiveSqlConnection(object):
    """meant to be used with a with statement to ensure proper closure"""
    def __enter__(self, path):
        self.con = sql.connect(path, isolation_level = "EXCLUSIVE")
        self.con.execute("BEGIN EXCLUSIVE")
        self.cur = self.con.cursor()
        return self

    def __exit__(self):
        self.con.commit()
        self.con.close()

然而,当我运行这个时,我得到错误:

with sql_lib.ExclusiveSqlConnection(self.output) as c:
TypeError: object.__new__() takes no parameters

1 个答案:

答案 0 :(得分:2)

__init__的构造函数(ExclusiveSqlConnection方法)需要path参数。

另一方面,__enter__不使用self以外的任何参数。

import sqlite3 as sql

class ExclusiveSqlConnection(object):
    """meant to be used with a with statement to ensure proper closure"""

    def __init__(self, path):
        self.path = path

    def __enter__(self):
        self.con = sql.connect(self.path, isolation_level = "EXCLUSIVE")
        self.con.execute("BEGIN EXCLUSIVE")
        self.cur = self.con.cursor()
        return self

    def __exit__(self, exception_type, exception_val, trace):
        self.con.commit()
        self.con.close()