django中異步調用第三方api接口,簡單記錄


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

完美!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM