【问题标题】:how to Async request in sanic parallel Work如何在 sanic 并行工作中异步请求
【发布时间】:2021-04-06 14:27:19
【问题描述】:

我无法从这段代码中释放主函数,以便并行完成任务并且我可以接收另一个 get。

在这段代码中,当我在 chrome http://0.0.0.0:8082/envioavisos?test1=AAAAAA&test2=test 中打开时,get_avisos_grupo() 函数将在 secuence 中执行而不是并行执行,直到函数结束并且无法向 http://0.0.0.0:8082/envioavisos?test1=AAAAAA&test2=test 发送另一个请求

#!/usr/bin/env python3
import asyncio
import time
from sanic import Sanic
from sanic.response import text
from datetime import datetime
import requests

avisos_ips = ['1.1.1.1','2.2.2.2']

app = Sanic(name='server')

async def get_avisos_grupo(ip_destino,test1,test2):
    try:
        try:
            print(datetime.now().strftime("%d/%m/%Y %H:%M:%S,%f"),'STEP 2',ip_destino)

            r = requests.post('http://{}:8081/avisosgrupo?test1={}&test2={}'.format(ip_destino,test1,test2), timeout=10)
            await asyncio.sleep(5)
        except Exception as e:
            print('TIME OUT',str(e))
            pass

    except Exception as e:
        print(str(e))
        pass


@app.route("/envioavisos", methods=['GET','POST'])
async def avisos_telegram_send(request): ## enviar avisos
    try:
        query_components = request.get_args(keep_blank_values=True)
        print(datetime.now().strftime("%d/%m/%Y %H:%M:%S,%f"),'>--------STEP 1',query_components['test1'][0])

        for ip_destino in avisos_ips:
            asyncio.ensure_future(get_avisos_grupo(ip_destino,query_components['test1'][0],query_components['test2'][0]))

    except Exception as e:
        print(str(e))
        pass
    print(datetime.now().strftime("%d/%m/%Y %H:%M:%S,%f"),'STEP 4')
    return text('ok')



if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8082, workers=4)

预期结果是并行发布所有内容。

我得到了这个结果

06/04/2021 16:25:18,669074 STEP 2 1.1.1.1
TIME OUT HTTPConnectionPool(host='1.1.1.1', port=8081): Max retries exceeded with url: '))
06/04/2021 16:25:28,684200 STEP 2 2.2.2.2
TIME OUT HTTPConnectionPool(host='2.2.2.2', port=8081): Max retries exceeded with url: '))

我希望有这样的东西

06/04/2021 16:25:18,669074 STEP 2 1.1.1.1
06/04/2021 16:25:28,684200 STEP 2 2.2.2.2
TIME OUT HTTPConnectionPool(host='1.1.1.1', port=8081): Max retries exceeded with url: '))
TIME OUT HTTPConnectionPool(host='2.2.2.2', port=8081): Max retries exceeded with url: '))

【问题讨论】:

    标签: python sanic


    【解决方案1】:

    Asyncio 不是并行操作的灵丹妙药。事实上,Sanic 也没有。它的作用是有效利用处理器,允许多个功能一次“推动球向前”一点点。

    一切都在一个线程和一个进程中运行。

    您遇到这种情况是因为您使用了阻塞的 HTTP 调用。您应该将 requests 替换为异步兼容实用程序,以便 Sanic 可以将请求放在一边,以便在传出操作发生时处理新请求。

    看看这个:

    https://sanicframework.org/en/guide/basics/handlers.html#a-word-about-async

    一个常见的错误!

    不要这样做!您需要 ping 一个网站。你用什么? pip install your-fav-request-library ?

    请尝试使用支持异步/等待的客户端。你的服务器会感谢你的。避免使用阻塞工具,而偏爱那些在异步生态系统中表现良好的工具。如果您需要建议,请查看 Awesome Sanic

    Sanic 在其测试包中使用 httpx (sanic-testing) ?。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2022-01-06
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多