django - sqlite 数据库表在测试时被锁定

标签 django database sqlite testing

我正在尝试将应用程序从 django 1.11.1 迁移到 django 2.0.1 测试设置为使用内存数据库中的 sqlite 运行。但是每个测试都失败了,因为 sqlite3.OperationalError: database table is locked 每个表。我如何找出它被锁定的原因?增加超时设置没有帮助。

我正在使用 LiveServerTestCase,所以我想测试必须在与内存数据库不同的线程中运行,并且由于某种原因它没有被共享。

最佳答案

我也点了这个。 LiveServerTestCase 是多线程的,因为 this got merged .

当我的被测应用程序发出多个请求时,这对我来说是个问题。然后,据我推测,LiveServer 生成线程来处理这些请求。这些请求然后导致写入 SQLite 数据库。这反过来又不喜欢多个写入线程。

有趣的是,runserver 知道--nothreading。但是测试服务器似乎缺少这样的选项。

以下代码片段为我带来了一个单线程测试服务器:

class LiveServerSingleThread(LiveServerThread):
    """Runs a single threaded server rather than multi threaded. Reverts https://github.com/django/django/pull/7832"""

    def _create_server(self):

        """
        the keep-alive fixes introduced in Django 2.1.4 (934acf1126995f6e6ccba5947ec8f7561633c27f)
        cause problems when serving the static files in a stream.
        We disable the helper handle method that calls handle_one_request multiple times.
        """
        QuietWSGIRequestHandler.handle = QuietWSGIRequestHandler.handle_one_request

        return WSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)


class LiveServerSingleThreadedTestCase(LiveServerTestCase):
    "A thin sub-class which only sets the single-threaded server as a class"
    server_thread_class = LiveServerSingleThread

然后,从 LiveServerSingleThreadedTestCase 而不是 LiveServerTestCase 派生您的测试类。

关于django - sqlite 数据库表在测试时被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353002/

相关文章:

python - 保存 Django 表单产生错误 : unorderable types: int() > str()

python - 模拟外部 HTTP 请求

sql-server - 插入到具有只读主键列的表

android - 存储较大的实际值会在 SQLite android 中产生不需要的结果?

mysql - Rails 4 迁移不向现有数据库添加字段

django - 在 Django Admin 中创建多个相关对象

Django ListView 忽略 get_Queryset 中的 Order_by

java - 有没有办法从操作系统访问(读/写)特定应用程序的 sqlite 数据库?

mysql - 与其他实体有随机关系的实体

mysql - MYSQL 插入数据库 MyISAM 速度慢