Как разместить группу запросов на 2 URL с помощью aiohttp - PullRequest
0 голосов
/ 03 июля 2019

У меня есть 2 URL и более 60 000 запросов.По сути, мне нужно отправлять каждый запрос на оба URL-адреса, затем сравнивать их ответы, но не ждать ответа, чтобы опубликовать другой запрос.

Я пытался сделать это с aiohttp и asyncio

import asyncio
import time
import aiohttp
import os

from aiofile import AIOFile

testURL = ""
prodURL = ""

directoryWithRequests = ''
directoryToWrite = ''

headers = {'content-type': 'application/soap+xml'}

i = 1


async def fetch(session, url, reqeust):
    global i
    async with session.post(url=url, data=reqeust.encode('utf-8'), headers=headers) as response:
        if response.status != 200:
            async with AIOFile(directoryToWrite + str(i) + '.xml', 'w') as afp:
                await afp.write(reqeust)
                i += 1
        return await response.text()


async def fetch_all(session, urls, request):
    results = await asyncio.gather(*[asyncio.create_task(fetch(session, url, request)) for url in urls])
    return results


async def asynchronousRequests(requestBody):
    urls = [testURL, prodURL]
    global i
    with open(requestBody) as my_file:
        body = my_file.read()

    async with aiohttp.ClientSession() as session:
        htmls = await fetch_all(session, urls, body)
        # some conditions

async def asynchronous():
    try:
        start = time.time()
        futures = [asynchronousRequests(directoryWithRequests + i) for i in os.listdir(directoryWithRequests)]
        for future in asyncio.as_completed(futures):
            result = await future

        print("Process took: {:.2f} seconds".format(time.time() - start))

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

if __name__ == '__main__':
    try:
        # AsyncronTest
        ioloop = asyncio.ProactorEventLoop()
        ioloop.run_until_complete(asynchronous())
        ioloop.close()
        if i == 1:
            print('Regress is OK')
        else:
            print('Number of requests to check = {}'.format(i))

    except Exception as e:
        print(e)

Я считаю, что приведенный выше код работает, но он создает N фьючерсов, где N равно количеству файлов запросов.Это приводит к некоторому типу ddos, потому что сервер не может отвечать на это количество запросов одновременно.

1 Ответ

0 голосов
/ 04 июля 2019

Нашли подходящее решение. В основном это только 2 асинхронные задачи:

tasks = [
                postRequest(testURL, client, body),
                postRequest(prodURL, client, body)
            ]
await asyncio.wait(tasks)

Это не та же производительность, что и в коде, о котором идет речь, с большим количеством запросов, но, как минимум, это не делает сервер слишком много.

...