[파이썬] Tornado와 SQLAlchemy 연동

Tornado is a powerful and scalable web framework for Python that allows you to build high-performance web applications. SQLAlchemy is a popular Object Relational Mapper (ORM) library for Python that provides a convenient way to interact with databases.

In this blog post, we will explore how to integrate Tornado and SQLAlchemy to efficiently manage database operations within your Tornado application.

Installation

Before we begin, make sure you have both Tornado and SQLAlchemy installed. You can install them using pip:

$ pip install tornado sqlalchemy

Configure SQLAlchemy

To connect Tornado with SQLAlchemy, we need to configure the SQLAlchemy engine. The engine is responsible for maintaining the database connection.

from sqlalchemy import create_engine

engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')

In the example above, we create an engine that connects to a PostgreSQL database. Replace username, password, and mydatabase with your actual database credentials.

Define Database Model

Next, let’s define a simple model using SQLAlchemy’s declarative base class.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)

In this example, we define a User model with three columns: id, username, and email. The __tablename__ attribute specifies the name of the database table.

Create Tornado Request Handler

Now, let’s create a Tornado request handler that interacts with the database using the SQLAlchemy engine.

import tornado.web

class UserHandler(tornado.web.RequestHandler):
    def get(self):
        with engine.connect() as conn:
            result = conn.execute(User.select())

            users = []
            for row in result:
                users.append({
                    'id': row.id,
                    'username': row.username,
                    'email': row.email,
                })

        self.write({'users': users})

In the get method of our request handler, we establish a connection to the database using the SQLAlchemy engine. Then, we execute a select query to retrieve all users from the users table.

The resulting rows are looped through and converted into a list of dictionaries. Finally, the output is returned as JSON using the Tornado write method.

Register Request Handler with Tornado Application

To complete the integration between Tornado and SQLAlchemy, we need to register our request handler with the Tornado application.

import tornado.ioloop
import tornado.web

app = tornado.web.Application([
    (r'/users', UserHandler),
])

if __name__ == '__main__':
    app.listen(8000)
    tornado.ioloop.IOLoop.current().start()

In this example, we create a Tornado application and register the UserHandler to handle requests to the /users URL. The application is then set to listen on port 8000.

Conclusion

By combining the power of Tornado and SQLAlchemy, we can build web applications with efficient and scalable database operations. Tornado provides a fast and asynchronous web framework, while SQLAlchemy simplifies database interaction with its ORM capabilities.

In this blog post, we explored the process of integrating Tornado with SQLAlchemy, from configuring the engine to defining the model, and finally creating a request handler to interact with the database.