[파이썬] Peewee Data conversion 및 adaptors

Peewee is a lightweight and easy-to-use Object Relational Mapping (ORM) library for Python. It provides a simple and intuitive way to interact with databases, abstracting away the complexities of SQL queries and data manipulation. In this article, we will explore how Peewee handles data conversion and adapters.

Data Conversion in Peewee

Peewee automatically converts data between Python objects and database-specific types based on the field definitions in your models. This makes it easy to store and retrieve data from the database without having to manually handle conversions.

Supported Data Types

Peewee supports a wide range of data types, including:

Custom Data Conversion

If you need to handle custom data types or want to modify the default conversion behavior, you can define custom converters. Peewee allows you to register converters that provide serialization and deserialization logic for specific data types.

Let’s say we have a custom class called Point that represents a point in a two-dimensional space. To store and retrieve instances of this class in the database, we can define a custom converter:

from peewee import *

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def point_to_db(value):
    return f"({value.x},{value.y})"

def db_to_point(value):
    x, y = map(int, value.strip("()").split(","))
    return Point(x, y)

database = SqliteDatabase(":memory:")

class MyModel(Model):
    my_point = TextField()

    class Meta:
        database = database

database.create_tables([MyModel])

database.register_adapter(Point, point_to_db)
database.register_converter("point", db_to_point)

point = Point(10, 20)
model = MyModel.create(my_point=point)

retrieved_model = MyModel.get(MyModel.my_point == point)
assert retrieved_model.my_point == point

In the above example, we define a Point class that represents a point in two-dimensional space. We then define two converter functions point_to_db and db_to_point to serialize and deserialize Point objects when storing and retrieving them from the database.

We register these converters with the SqliteDatabase instance and use them in a MyModel class that has a my_point field of type TextField.

Adapters in Peewee

Peewee also provides a mechanism called adapters that allow you to define custom behavior for specific database engines. Adapters can be used to handle database-specific features or to override default behavior.

Built-in Adapters

Peewee comes with built-in adapters for popular databases such as SQLite, MySQL, and PostgreSQL. These adapters provide the necessary logic to interact with the specific database engines and are automatically used when connecting to the respective databases.

Custom Adapters

If you need to connect to a database that is not supported out-of-the-box or want to extend an existing adapter’s functionality, you can define custom adapters. Custom adapters allow you to handle the intricacies of a specific database engine and provide the necessary methods to interact with it.

Here’s an example of defining a custom adapter for a hypothetical database engine called “MyDatabase”:

from peewee import *

class MyDatabaseAdapter(Adapter):
    def connect(self, database, **kwargs):
        # Connect to the MyDatabase engine
        pass

    def execute_sql(self, sql, params=None, commit=True):
        # Execute the given SQL statement on the MyDatabase engine
        pass

    def close(self):
        # Close the connection to the MyDatabase engine
        pass

database = MyDatabaseAdapter("mydatabase://user:password@localhost/mydatabase")

In the above example, we define a MyDatabaseAdapter class that inherits from Adapter. We then provide the necessary methods connect, execute_sql, and close to handle the connection, SQL execution, and connection closing logic for the “MyDatabase” engine.

We can then use this custom adapter when connecting to the “MyDatabase” engine by passing its URL to the MyDatabaseAdapter constructor.

Conclusion

Understanding how Peewee handles data conversion and adapters is essential for working effectively with databases in Python. Peewee’s support for custom data converters and adapters makes it a versatile ORM that can be easily adapted to different database engines and data types.