[파이썬] aiohttp POST 요청 수행하기

In this blog post, we will learn how to perform a POST request using the aiohttp library in Python.

Installing aiohttp

First, we need to install the aiohttp library. You can do this by running the following command:

pip install aiohttp

Importing aiohttp

Next, we need to import the aiohttp library in our Python script:

import aiohttp

Sending a POST Request

To send a POST request, we can use the aiohttp.ClientSession class provided by the aiohttp library.

Here is an example of sending a POST request to a server:

import aiohttp
import asyncio

async def send_post_request():
    url = "https://example.com/api/endpoint"
    data = {"key1": "value1", "key2": "value2"}
    
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=data) as response:
            if response.status == 200:
                response_json = await response.json()
                print(response_json)
            else:
                print("Request failed")
            
loop = asyncio.get_event_loop()
loop.run_until_complete(send_post_request())

In the above example, we define an async function send_post_request() that sends a POST request to the specified URL with the given data using session.post(url, data=data). We then check the status code of the response and print the response JSON if the status code is 200 (OK). Otherwise, we print “Request failed”.

Running the Code

To run the code, simply save it to a file, such as post_request.py, and execute the script using the Python interpreter:

python post_request.py

Ensure that you have an active internet connection, as the code makes a request to an external server.

Conclusion

In this blog post, we learned how to use the aiohttp library in Python to send a POST request. aiohttp provides a convenient and efficient way to make asynchronous HTTP requests in Python. You can now integrate this code into your own projects to perform POST requests. Happy coding!