简单得用个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"

完美!!

相关文章:

  • 2022-01-29
  • 2022-01-01
  • 2021-10-05
  • 2022-02-05
  • 2021-11-02
  • 2021-06-22
  • 2021-11-20
  • 2021-06-08
猜你喜欢
  • 2022-02-03
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2021-11-20
  • 2021-12-26
  • 2022-01-08
相关资源
相似解决方案