简单得用个demo,记录使用中遇到得问题,和解决方法
from concurrent.futures import ThreadPoolExecutor import time import asyncio def add_host_api(): add_host(monitor_api_lt) async def main(loop): executor = ThreadPoolExecutor() await loop.run_in_executor(executor, add_host_api) loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) loop.close()
代码里add_host_api封装得是第三方得api接口
此时直接使用,可能会出现下面问题
There is no current event loop in thread 'Thread-1' 解决:
将 loop = asyncio.get_event_loop() 替换成 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
紧接着可能会出现
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async 解决: 在settings文件中加入 os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
完美!!