zoukankan      html  css  js  c++  java
  • 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"

    完美!!

  • 相关阅读:
    0.1.3 set的用法
    JoinPoint
    砝码组合(dfs)
    强大的【环绕通知】
    applicationContext.xml 模板
    各种jar包
    装饰博客(二)添加宠物
    装饰博客(一)添加背景图片
    拖拽功能的实现
    点击之后连接qq
  • 原文地址:https://www.cnblogs.com/leisunny/p/13901806.html
Copyright © 2011-2022 走看看