Django sqlite3超时无效 [英] Django sqlite3 timeout has no effect

查看:116
本文介绍了Django sqlite3超时无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中进行了一个简单的集成测试,该测试生成了一个Celery工人来运行作业,该作业将记录写入数据库.Django线程还将一条记录写入数据库.因为这是一个测试,所以我使用默认的内存sqlite3数据库.没有正在使用的交易.

I have a simple integration test in Django that spawns a single Celery worker to run a job, which writes a record to the database. The Django thread also writes a record to the database. Because it's a test, I use the default in-memory sqlite3 database. There are no transactions being used.

我经常遇到此错误:

django.db.utils.OperationalError: database table is locked

根据Django文档,这是由于一个连接在等待另一个连接完成时超时.它是比sqlite在默认配置中无法处理的并发性更多".考虑到两个线程中的两个记录,这似乎很奇怪.尽管如此,同一位文档说增加超时选项以强制连接等待更长的时间.好的,我将数据库设置更改为此:

which according to the Django docs is due to one connection timing out while waiting for another to finish. It's "more concurrency than sqlite can handle in default configuration". This seems strange given that it's two records in two threads. Nevertheless, the same docs say to increase the timeout option to force connections to wait longer. Ok, I change my database settings to this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'OPTIONS': {'timeout': 10000000},
    }
}

这无效.该错误仍然出现,并且显然没有等待1e7秒或1e7毫秒或1e7微秒.我还缺少其他设置吗?

This has no effect. The error still appears and it clearly has not waited 1e7 seconds or 1e7 milliseconds or 1e7 microseconds before doing so. Is there an additional setting I'm missing?

我尝试了Python 3.5和Python 3.6以及Django 1.11和Django 2.0.

I have tried both Python 3.5 and Python 3.6 and both Django 1.11 and Django 2.0.

推荐答案

我遇到了同样的问题,我的实验给了我以下内容:

I had the same issue and my experiments gave me the following:

  1. 我发现Django在测试模式下使用内存中的SQLite DB,直到您明确更改它为止.这就解释了为什么我只能在单元测试中看到该问题.要强制Django在 settings.py 中显式设置文件 DATABASES-> TEST-> NAME 的文件中使用SQLite DB.例如这样的

  1. I've figured out that Django uses in-memory SQLite DB in the test mode until you explicitly change this. That explains why I only see that problem in my unit tests. To force Django to use SQLite DB in the file set DATABASES->TEST->NAME explicitly in your settings.py. For example like this:

DATABASES = {
    'default': {
        ...
        'TEST': {
            'NAME': 'testdb.sqlite3',
        },
    },
}

  • 将超时值设置为大于2147483.647(看起来很熟悉,对吗?:-))将禁用超时(或将其设置为可忽略的较小值).

  • Setting timeout value larger than 2147483.647 (looks familiar, right? :-) ) disables timeout (or sets it to negligibly small value).

    据我了解,问题的根源是当SQLite使用共享缓存时,根本不遵守超时值.

    As far as I understand, the root of the problem is that when SQLite uses the shared cache the timeout value is not respected at all.

    这篇关于Django sqlite3超时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆