【问题标题】:Django transaction doesn't work with raw SQL queriesDjango 事务不适用于原始 SQL 查询
【发布时间】:2021-02-19 06:49:55
【问题描述】:

因为我厌倦了 Django DB 驱动程序的隐式行为,所以我使用了以下带有普通 Postgres 事务的代码:

from django.db import transaction, connection
from concurrent.futures.thread import ThreadPoolExecutor

def commit_or_rollback(commit: bool):
    query = "COMMIT" if commit else "ROLLBACK"
    with connection.cursor() as cursor:
        cursor.execute(query)

def insert(query, parameter):
    with connection.cursor() as cursor:
        cursor.execute(query, parameter)

def insert_with_threads():
    insert_pool = ThreadPoolExecutor(max_workers=4)
    query = 'INSERT INTO a_table VALUES (%s)'
    parameters = [...]
    for parameter in parameters:
        insert_pool.submit(insert, query, parameter)

# "Main" program
try:
    with connection.cursor() as cursor:
        cursor.execute("BEGIN")

    insert_with_threads()  # Could raise any of the caught exceptions

except CustomException1:
    commit_or_rollback(False)
except CustomException2:
    commit_or_rollback(False)
except Exception as e:
    commit_or_rollback(False)
    # Some general stuff
else:
    commit_or_rollback(True)

但是没有任何东西回滚,我尝试过使用transaction.atomic()set_autocommit()set_autocommit() 原始BEGIN,但没有任何效果。线程会破坏东西吗?打开多个游标有问题吗?

任何形式的帮助都将不胜感激

【问题讨论】:

  • 是: 打开多个游标有问题吗?

标签: python django postgresql psycopg2


【解决方案1】:

这肯定是多线程的问题(我使用的是 ThreadPoolExecutor)。现在我正在使用 ProcessPoolExecutor 并按预期工作

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2015-11-21
    • 2012-03-16
    • 2017-11-18
    • 2018-05-15
    • 2013-04-17
    • 2013-05-06
    • 2019-08-05
    • 2017-04-08
    相关资源
    最近更新 更多