본문 바로가기

Python

aiohttp: async requests code example

728x90
반응형

install: 

pip install aiohttp

 

 

다수의 request를 비동기적으로 요청하기 (예제에서는 1000번)

 

- put 요청 기준 - post도 동일한 방식 (메소드만 put -> post 변경)

import aiohttp
import asyncio


async def send_put_request(session, url, data, headers):
    async with session.put(url, json=data, headers=headers) as response:
        return response.status, await response.text()


async def main(url, data, headers):
    async with aiohttp.ClientSession() as session:
        tasks = [send_put_request(session, url, data, headers) for _ in range(1000)]
        responses = await asyncio.gather(*tasks)
        print(responses)  # Prints status and response text of each request


if __name__ == "__main__":
    # URL you are sending the PUT request to
    url = "http://localhost:8000/api/v1/board/free/206"

    # Headers you may need to send (e.g., Content-Type, Authorization)
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token'
    }

    # Data to be sent in JSON format
    data = {
        "wr_subject": "string",
        "wr_content": "",
        "wr_name": "",
        "wr_password": "",
        "wr_email": "",
        "wr_homepage": "",
        "wr_link1": "",
        "wr_link2": "",
        "wr_option": "",
        "html": "",
        "mail": "",
        "secret": "",
        "ca_name": "",
        "notice": "false",
        "parent_id": 0,
        "additionalProp1": {}
    }

    asyncio.run(main(url, data, headers))

 

- delete 요청 기준 (data 변수와 관련된 부분을 제거) - get도 동일한 방식 (메소드만 delete -> get 변경)

import aiohttp
import asyncio

async def send_put_request(session, url, headers):
    async with session.delete(url, headers=headers) as response:
        return response.status, await response.text()

async def main(url, headers):
    async with aiohttp.ClientSession() as session:
        tasks = [send_put_request(session, url, headers) for _ in range(1000)]
        responses = await asyncio.gather(*tasks)
        print(responses)  # Prints status and response text of each request

if __name__ == "__main__":
    # URL you are sending the PUT request to
    url = "http://localhost:8000/api/v1/board/free/1"

    # Headers you may need to send (e.g., Content-Type, Authorization)
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token'
    }

    asyncio.run(main(url, headers=headers))
728x90
반응형