[파이썬] Peewee Database router 설정

Peewee is a lightweight and easy-to-use Python ORM (Object-Relational Mapping) library. It allows you to interact with various databases using a simple and intuitive API. One of the powerful features of Peewee is its ability to support multiple databases simultaneously.

To achieve this, Peewee provides a feature called Database Routers. A database router allows you to define rules for selecting a specific database based on the model being accessed. This can be useful in scenarios where you need to distribute data across different databases or interact with different types of databases.

In this blog post, we will explore how to configure and use a database router in Peewee.

Setting Up the Database Connection

Before we dive into the database router, let’s start by setting up the connection to the databases we want to work with. For simplicity, we’ll consider two databases: MySQL and SQLite.

First, we need to install the required packages for Peewee and the database drivers. Open your terminal and run the following commands:

pip install peewee
pip install mysqlclient
pip install pysqlite3

Next, create a new python file and import the necessary modules:

from peewee import *

Now, let’s define the connections to MySQL and SQLite databases:

mysql_db = MySQLDatabase('my_database', user='root', password='password', host='localhost', port=3306)
sqlite_db = SqliteDatabase('my_database.sqlite')

Replace my_database with the name of the respective databases.

Implementing the Database Router

To implement a database router, we need to subclass the peewee.DatabaseRouter class and override its methods.

Here’s an example implementation of a database router that routes models to the appropriate database based on a prefix in the model’s name:

class PrefixDatabaseRouter(object):
    def __init__(self, prefix_map):
        self.prefix_map = prefix_map

    def db_for_table(self, model, **kwargs):
        for prefix, database in self.prefix_map.items():
            if model.__name__.startswith(prefix):
                return database

    def db_for_read(self, model, **kwargs):
        return self.db_for_table(model)

    def db_for_write(self, model, **kwargs):
        return self.db_for_table(model)

In this example, the prefix_map parameter is a dictionary that maps prefixes to database connections. The db_for_table method determines the appropriate database connection based on the model’s prefix. The db_for_read and db_for_write methods call db_for_table for simplicity.

Configuring the Database Router

To configure the database router, we need to create an instance of it and add it to the database parameter when defining the Peewee models.

Let’s define two simple models, MySQLModel and SQLiteModel, and associate them with the corresponding databases:

class MySQLModel(Model):
    class Meta:
        database = mysql_db


class SQLiteModel(Model):
    class Meta:
        database = sqlite_db

Now, let’s configure the database router and assign it to Peewee’s DatabaseRouter:

prefix_map = {
    'mysql_': mysql_db,
    'sqlite_': sqlite_db
}

database_router = PrefixDatabaseRouter(prefix_map)
database_proxy.initialize(database_router)

In this example, the prefix mysql_ is associated with the MySQL database, and the prefix sqlite_ is associated with the SQLite database.

Testing the Database Router

To test our database router, let’s create some sample data in both databases using our models:

mysql_model = MySQLModel.create(name='MySQL Model')
sqlite_model = SQLiteModel.create(name='SQLite Model')

Now, let’s retrieve the data from both databases:

mysql_models = MySQLModel.select()
sqlite_models = SQLiteModel.select()

for model in mysql_models:
    print(f'MySQL Model: {model.name}')

for model in sqlite_models:
    print(f'SQLite Model: {model.name}')

If everything is set up correctly, you should see the names of the models printed for the corresponding databases.

Conclusion

In this blog post, we covered how to configure and use a database router in Peewee. The database router feature allows you to distribute data across multiple databases or interact with different types of databases seamlessly. With Peewee’s simple API and powerful features, managing multiple databases becomes easier and more flexible.

Stay tuned for more articles on Peewee and other Python frameworks. Happy coding!