簡單得用個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"
完美!!