【发布时间】:2020-02-15 19:33:51
【问题描述】:
我在异步代码中使用 Django ORM。一切正常,所有测试都通过。但是,数据库连接在测试后没有正确关闭。这是一个例子:
from asgiref.sync import sync_to_async, async_to_sync
@sync_to_async
def count_books():
return Book.objects.count()
class FooTest(TestCase):
def setUp(self):
Book.objects.create(title='Haha')
def test1(self):
import asyncio
c = asyncio.run(count_books())
self.assertEqual(1, c)
def test2(self):
c = async_to_sync(count_books)()
self.assertEqual(1, c)
Postgres 错误:
django.db.utils.OperationalError: database "test_mydbname" is being accessed by other users
Sqlite 错误:
sqlite3.OperationalError: database table is locked: test_mydbname
我尝试将 django-channels 中的 sync_to_async 与 database_sync_to_async 交换,但这并没有改变任何东西。
我该如何解决这个问题?
【问题讨论】:
-
你在尝试 django 3.0 使用电机吗?
标签: django python-asyncio django-channels django-tests asgi