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任务时)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
|
在Django单个视图中使用ThreadPoolExecutor实例代码如下(有多个IO任务时)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
附tornado中不依赖异步库实现异步非阻塞
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
参考 https://blog.csdn.net/qq_34367804/article/details/75046718
https://www.cnblogs.com/zhaof/p/8490045.html
https://stackoverflow.com/questions/41594266/asyncio-with-django