【发布时间】:2021-01-07 14:55:32
【问题描述】:
我正在编写一个在数据库中随机创建 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
在我继续破脑袋之前,我问:有没有可能实现我的愿望?如果是这样,我应该如何进行?
非常感谢!
【问题讨论】:
-
您是否可以同时运行多个异步方法,但在其中您有
await sync_to_async(write_to_db)(**props_as_primitives)? -
对不起,我不明白你的问题。我的问题其实很简单:我想让
create_orders函数的第一个循环异步。 -
首先,您正在创建 5M 行,这肯定需要时间(也取决于您的数据库的高可扩展性)。其次,调用
asyncdb connection 可能对您没有帮助,因为它们必须按 "sequential" 顺序进行(简单示例:您必须在创建订单之前创建客户实例)。 -
我宁愿在尝试移植到 async 解决方案之前尝试清理我的代码。
-
@JPG 您可以从客户已经创建的代码中看到。此外,订单不需要按“顺序”顺序排列。最后,简单地说“清理你的代码”实际上有助于零。
标签: django asynchronous python-asyncio