gpt4 book ai didi

Django:如何使用两个同时连接到单个数据库?

转载 作者:行者123 更新时间:2023-12-02 08:10:12 24 4
gpt4 key购买 nike

让我们得到代码:

def some_function():
with transaction.atomic():
# some code which writes to DB

try:
call_method_which_may_raise_exception()
except KnownException as e:
save_some_data_about_exception_to_database(e)
raise

# other code which writes to DB

问题是当我重新引发异常时,我的“一些数据”也会丢失,因为它是在同一事务中进行的。是否有上下文或其他东西可以在单独的事务/连接中执行代码?

有一点是,代码的架构师很糟糕。在正常流程中,不需要 save_some_data...

正如他们所说的提议的解决方案:

def some_function():
exception_to_save = None
try:
with transaction.atomic():
# some code which writes to DB

try:
call_method_which_may_raise_exception()
except KnownException as e:
exception_to_save = e
raise

# other code which writes to DB
except Exception as e:
if exception_to_save:
save_some_data_about_exception_to_database(exception_to_save)
raise

但是肮脏的代码会变得更加肮脏。

我更希望它是这样的:

def some_function():
with transaction.atomic():
# some code which writes to DB

try:
call_method_which_may_raise_exception()
except KnownException as e:
with transaction.separate_connection():
save_some_data_about_exception_to_database(e)
raise

# other code which writes to DB

欢迎任何想法!

最佳答案

我认为没有任何理由使用单独的连接。仅仅使用较低级别的 API 还不够吗?

def some_function():
transaction.set_autocommit(False)
try:
call_method_which_may_raise_exception()
except KnownException as e:
transaction.rollback()
save_some_data_about_exception_to_database(e)
raise
finally:
transaction.commit()
transaction.set_autocommit(True)

关于Django:如何使用两个同时连接到单个数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414110/

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