【问题标题】:Django support for asynchronous database enginesDjango 对异步数据库引擎的支持
【发布时间】:2022-06-17 15:51:44
【问题描述】:

我找不到有关 django 对异步数据库引擎的支持的信息。例如,对于 postgresql django 只支持 psycopg2 库,它是完全同步的,不支持其他任何东西,对于 sqlite django 只支持同步的 sqlite3 库。所以我在 django 中没有很好的定位,当然我可能会弄错,但是如果 django asgi 不支持异步数据库引擎(我的意思是,那么所有异步代码都变成同步的),那它的意义是什么?

第二个问题,有没有办法在django中使用异步引擎?

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 你读过the docs吗?
  • @IainShelvington 感谢您的反馈。是的,我做到了,文档说我需要使用 sync_to_async() 装饰器,但我不知道它是如何工作的,以及它是否使代码完全异步

标签: python django asynchronous database-engine


【解决方案1】:

这是来自 Django 文档

*您在寻找什么样的数据库异步支持? *

# DJANGO_SETTINGS_MODULE=settings.py python -m asyncio
>>> import asyncio
>>> from asgiref.sync import sync_to_async
>>> from django.db import connection
>>> # In an async context so you cannot use the database directly:
>>> connection.cursor()

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from
an async context - use a thread or sync_to_async.
>>> # Nor can you pass resolved connection attributes across threads:
>>> await sync_to_async(connection.cursor)()
...
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread
can only be used in that same thread. The object with alias 'default' was
created in thread id 4371465600 and this is thread id 6131478528.

https://docs.djangoproject.com/en/4.0/topics/async/

【讨论】:

  • 我说我在找异步数据库引擎
【解决方案2】:

据我所知,Django ORM 中不支持异步。所以你应该考虑使用不同的框架或集成不同的ORM,如sqlalchemy

这是他们在文档中所说的: “我们仍在努力为 ORM 和 Django 的其他部分提供异步支持。您可以在未来的版本中看到这一点。现在,您可以使用 sync_to_async() 适配器与 Django 的同步部分进行交互。有还有一系列可以集成的异步原生 Python 库。”

第二个问题:Configuring Django to use SQLAlchemy

但是,如果您没有很多 django 绑定的书面代码,我强烈建议您考虑切换框架。类似于FastAPI,或aiohttp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2010-09-21
    • 2011-06-07
    • 2011-03-22
    相关资源
    最近更新 更多