如何在django视图中使用asyncio(协程)和ThreadPoolExecutor(多线程)
Django视图函数执行,不在主线程中,直接 loop = asyncio.new_event_loop() # 更不能 loop = asyncio.get_event_loop() 会触发 RuntimeError: There is no current event loop in thread 因为asyncio程序中的每个线程都有自己的事件循环,但它只会在主线程中为你自动创建一个事件循环。所以如果你asyncio.get_event_loop在主线程中调用一次,它将自动创建一个循环对象并将其设置为默认值,但是如果你在一个子线程中再次调用它,你会得到这个错误。相反,您需要在线程启动时显式创建/设置事件循环: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) 在Django单个视图中使用asyncio实例代码如下(有多个IO任务时) from django.views import View import asyncio import time from django.http import JsonResponse class TestAsyncioView(View): def get(self, request, *args, **kwargs): """ 利用asyncio和async