[파이썬] aiohttp 비동기 SQL 데이터베이스 연동

With the increasing popularity of asynchronous programming in Python, it is important to have efficient and scalable ways to connect to databases while utilizing the benefits of asynchronous workflows. One popular framework for asynchronous web development in Python is aiohttp. In this blog post, we will explore how to connect to an SQL database asynchronously using aiohttp in Python.

Installing Dependencies

Before we start, let’s make sure we have the necessary dependencies installed. To connect to an SQL database asynchronously, we’ll need the following packages:

To install these packages, use pip:

pip install aiohttp aiomysql  # for MySQL
pip install aiohttp aiopg  # for PostgreSQL

Connecting to an SQL Database

To connect to an SQL database asynchronously with aiohttp, follow these steps:

  1. Import the necessary modules:
import aiohttp
import aiomysql  # or aiopg for PostgreSQL
  1. Create a function to open the database connection and return a connection pool object. This function will be called at the beginning of your application to establish the connection:
async def create_db_pool(app):
    pool = await aiomysql.create_pool(host='localhost', port=3306, user='your_username', password='your_password', db='your_database')
    app['db_pool'] = pool  # store the connection pool object in the app instance

app = aiohttp.web.Application()
app.on_startup.append(create_db_pool)  # hook the function to the app startup

Replace the connection parameters (host, port, user, password, db) with your own database details.

  1. Use the connection pool to execute SQL queries asynchronously. You can create separate functions for different database operations, such as retrieving data or updating records:
async def fetch_data(request):
    async with request.app['db_pool'].acquire() as conn:
        async with conn.cursor() as cursor:
            await cursor.execute("SELECT * FROM your_table")
            result = await cursor.fetchall()
    
    return aiohttp.web.json_response(result)

In the above example, we use acquire() to acquire a connection from the pool, and cursor() to execute the SQL query. The fetchall() method returns all the rows from the table as a result.

  1. Register the route for fetching data in your aiohttp application:
app.router.add_get('/data', fetch_data)

Finally, start the aiohttp application and you’re ready to go:

aiohttp.web.run_app(app)

You have now successfully connected to an SQL database asynchronously using aiohttp in Python. By leveraging the power of asynchronous programming, you can efficiently handle multiple concurrent database requests and build high-performance web applications.

Remember to modify the code according to your specific database and application requirements. Happy coding!