我在异步代码中使用 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
但这并没有改变任何东西。
我怎样才能解决这个问题?