Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.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_Psycopg2 - Fatal编程技术网

Python 在类中重新使用psycopg2连接的最佳实践?

Python 在类中重新使用psycopg2连接的最佳实践?,python,psycopg2,Python,Psycopg2,假设我有一个类来创建红移对象依赖项。我想创建一个连接,然后将其重新用于许多不同的事务 我是否应该在uuu init_uuuuu函数中创建它,然后在uuu del_uuuu语句中设置self.conn.close以模拟with或try/finally模型 编辑: 以下是我的想法: class DatabaseConn: def __init__(self, env: DBEnvironment = DBEnvironment.PROD): """ A dat

假设我有一个类来创建红移对象依赖项。我想创建一个连接,然后将其重新用于许多不同的事务

我是否应该在uuu init_uuuuu函数中创建它,然后在uuu del_uuuu语句中设置self.conn.close以模拟with或try/finally模型

编辑: 以下是我的想法:

class DatabaseConn:
    def __init__(self, env: DBEnvironment = DBEnvironment.PROD):
        """
        A database connection that can be safely instantiated once, and then 
        passed around inside a class or between functions.

        :param env: The environment to connect to, choices are `DEV` and 
         `PROD`. 
        """
        self._conn = ppg2.connect(**env.value)

    def __del__(self):
        self._conn.close()

    def execute(
            self,
            query_or_stmt: str,
            has_res: bool = True) -> Optional[List[Tuple[Any]]]:
        """
        Creates a new cursor object, and executes the query/statement.  If 
        `has_res` is `True`, then it returns the list of tuple results.

        :param query_or_stmt: The query or statement to run.
        :param has_res: Whether or not results should be returned.

        :return: If `has_res` is `True`, then a list of tuples. 
        """
        cur = self._conn.cursor()
        cur.execute(query_or_stmt)
        if has_res:
            return cur.fetchall()

    def return_cursor(self):
        """
        :return: A psycopg2 cursor. 
        """
        return self._conn.cursor()

我建议避免使用del作为析构函数,因为它的调用模式是不确定的,而且根本不能保证被调用

如果您想将资源作为有界var行为获取,可以通过使用contextlib模块来实现

此示例来自python文档,位于:

这种方法的缺点是需要对资源的上下文进行编码


另一种方法是编写一个真正的析构函数,当连接引用计数器达到0时调用该析构函数。这与您最初使用_udel_uuu的想法非常相似,但为了避免直接使用_udel_u的许多问题,请使用。

我添加了自己的代码。finalize函数不能接受对象的有界方法,因此我无法传入连接本身以调用其close方法。你能看到有什么办法吗?
from contextlib import contextmanager

@contextmanager
def tag(name):
    print("<%s>" % name)
    yield
    print("</%s>" % name)

>>> with tag("h1"):
...    print("foo")
...
<h1>
foo
</h1>