gpt4 book ai didi

python - sqlalchemy:使用装饰器为多个函数提供线程安全 session

转载 作者:行者123 更新时间:2023-11-28 16:36:43 24 4
gpt4 key购买 nike

我正在研究类似 here 的东西(带有 sqlalchemy 的多线程应用程序),所以我明白,我应该为每个数据库查询创建一个新 session 。

我想知道,如果为每个需要 DB 访问的方法使用装饰器是否有意义,或者是否存在使用这种方法的陷阱。装饰器是按照 the last example here 构建的.

def dbconnect(func):
def inner(*args, **kwargs):
session = Session() # with all the requirements
try:
func(*args, session=session, **kwargs)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return inner

@dbconnect
def some_function(some, arguments, session)
session.query(...) # no commit, close, rollback required

some_function("many", "different_arguments")
#session is not required, since provided by decorator

这将使为任何函数提供线程安全的数据库访问变得相当容易,而不需要实现整个 try-except-finally-stuff 冗余,但我不确定这种方法是否是故障安全的和 pythonic,或者是否存在其他最佳实践。

最佳答案

我认为在这里使用 scoped_session 是有意义的,可能是这样的:

session_factory = sessionmaker(bind=some_engine)
Session = scoped_session(session_factory)

def dbconnect(func):
def inner(*args, **kwargs):
session = Session() # (this is now a scoped session)
try:
func(*args, **kwargs) # No need to pass session explicitly
session.commit()
except:
session.rollback()
raise
finally:
Session.remove() # NOTE: *remove* rather than *close* here
return inner

@dbconnect
def some_function(some, arguments):
session = Session()
# 'session' is now a handle to the *same* session as in the decorator
session.query(...) # no commit, close, rollback required

some_function("many", "different_arguments")
#session is not required, since provided by decorator

(警告:未经测试)

关于python - sqlalchemy:使用装饰器为多个函数提供线程安全 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25156264/

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