gpt4 book ai didi

python - 使用装饰器通过 psycopg2 访问数据库

转载 作者:行者123 更新时间:2023-12-04 18:02:36 28 4
gpt4 key购买 nike

我正在构建一个模型,该模型在 Postgresql 数据库中执行大部分计算(出于性能原因)。它看起来有点像这样:

def sql_func1(conn):
# prepare some data, crunch some number, etc.
curs = conn.cursor()
curs.execute("SOME SQL COMMAND")
curs.commit()
curs.close()

if __name__ == "__main__":
connection = psycopg2.connect(dbname='name', user='user', password='pass', host='localhost', port=1234)
sql_func1(conn)
sql_func2(conn)
sql_func3(conn)
connection.close()

该脚本使用了大约 30 个单独的函数,例如 sql_func1。显然一直在每个函数中管理连接和游标有点别扭。因此,我开始使用描述的装饰器 here .现在我可以简单地用装饰器 @db_connect 包装 sql_func1 并从那里传递连接。但是,这意味着我一直在打开和关闭连接,这也不是一个好习惯。 psycopg2 FAQ说:

Creating a connection can be slow (think of SSL over TCP) so the best practice is to create a single connection and keep it open as long as required. It is also good practice to rollback or commit frequently (even after a single SELECT statement) to make sure the backend is never left “idle in transaction”. See also psycopg2.pool for lightweight connection pooling.

能否请您给我一些见解,这对我来说是一种理想的做法。我是否应该使用传递 cursor 对象而不是 connection 的装饰器?如果是这样,请提供装饰器的代码示例。由于我是编程新手,如果您认为我的整体方法有误,请告诉我。

最佳答案

如何将连接存储在全局变量中而不在 finally block 中关闭它?像这样(根据您链接的示例):

cnn = None
def with_connection(f):

def with_connection_(*args, **kwargs):
global cnn
if not cnn:
cnn = psycopg.connect(DSN)
try:
rv = f(cnn, *args, **kwargs)
except Exception, e:
cnn.rollback()
raise
else:
cnn.commit() # or maybe not
return rv

return with_connection_

关于python - 使用装饰器通过 psycopg2 访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32537281/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com