gpt4 book ai didi

django - 可以在 django 中异步执行数据库操作吗?

转载 作者:行者123 更新时间:2023-12-03 18:57:18 26 4
gpt4 key购买 nike

我正在编写一个命令来在数据库中随机创建 500 万个订单。

def constrained_sum_sample(
number_of_integers: int, total: Optional[int] = 5000000
) -> int:
"""Return a randomly chosen list of n positive integers summing to total.

Args:
number_of_integers (int): The number of integers;
total (Optional[int]): The total sum. Defaults to 5000000.

Yields:
(int): The integers whose the sum is equals to total.
"""

dividers = sorted(sample(range(1, total), number_of_integers - 1))
for i, j in zip(dividers + [total], [0] + dividers):
yield i - j


def create_orders():
customers = Customer.objects.all()
number_of_customers = Customer.objects.count()
for customer, number_of_orders in zip(
customers,
constrained_sum_sample(number_of_integers=number_of_customers),
):
for _ in range(number_of_orders):
create_order(customer=customer)
number_of_customers将至少大于 1k 并且 create_order函数至少执行 5 次 db 操作(一个创建订单,一个随机获取订单的商店,一个创建订单项目(最多可以达到 30 个,也是随机的),一个获取项目的产品(或更高)但等于项目)和一个来创建销售说明。
正如您可能怀疑这需要很长时间才能完成。我曾尝试异步执行这些操作,但未成功。我的所有尝试(至少有十多次;其中大多数使用 sync_to_async )都引发了以下错误:
SynchronousOnlyOperation you cannot call this from an async context - use a thread or sync_to_async
在我继续破头之前,我问:有可能实现我的愿望吗?如果是这样,我应该如何进行?
非常感谢!

最佳答案

尚不支持,但正在开发中。
Django 3.1 正式支持 View 和中间件,但是如果您尝试在异步函数中调用 ORM,您将获得 SynchronousOnlyOperation。
如果您需要从异步函数调用 DB,他们提供了帮助程序实用程序,例如:
async_to_sync 和 sync_to_async 在线程或协程模式之间切换,如下所示:

from asgiref.sync import sync_to_async

results = await sync_to_async(Blog.objects.get, thread_sensitive=True)(pk=123)
如果您需要排队调用 DB,我们曾经使用 celery 或 rabbitMQ 等任务队列。
  • 顺便说一句,如果你真的知道你在做什么,你可以称之为但你的责任
    只需关闭异步安全,但要注意数据丢失和完整性错误
  • #settings.py
    DJANGO_ALLOW_ASYNC_UNSAFE=True

    The reason this is needed in Django is that many libraries, specifically database adapters, require that they are accessed in the same thread that they were created in. Also a lot of existing Django code assumes it all runs in the same thread, e.g. middleware adding things to a request for later use in views.


    发行说明中有更多有趣的消息:
    https://docs.djangoproject.com/en/3.1/topics/async/

    关于django - 可以在 django 中异步执行数据库操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65614708/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com