sanic并行工作中如何异步请求

2024-09-28 22:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在这段代码中,当我在chromehttp://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: '))

Tags: importiphostgetdatetimetimeportstep
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:01

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

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

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

看看这个:

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

A common mistake!

Don't do this! You need to ping a website. What do you use? pip install your-fav-request-library 🙈

Instead, try using a client that is async/await capable. Your server will thank you. Avoid using blocking tools, and favor those that play well in the asynchronous ecosystem. If you need recommendations, check out Awesome Sanic

Sanic uses httpx inside of its testing package (sanic-testing) 😉.

相关问题 更多 >