[파이썬] Peewee Signal 사용

Peewee is a lightweight ORM (Object-Relational Mapping) library for Python, which provides an easy way to interact with databases. One of the powerful features of Peewee is its Signal module, which allows you to add custom callbacks to certain events happening in your database models.

In this blog post, we will explore how to use Peewee Signal to enhance the functionality of our Python applications.

Getting Started

To begin using Peewee Signal, you need to make sure you have Peewee installed. You can install it using pip:

$ pip install peewee

Once you have Peewee installed, you can import the necessary classes from the Signal module:

from peewee import Model
from playhouse.signals import pre_save, post_save, pre_delete, post_delete

class MyModel(Model):
    # Model fields and methods here

# Connect signals to your model
pre_save.connect(my_pre_save_callback, sender=MyModel)
post_save.connect(my_post_save_callback, sender=MyModel)
pre_delete.connect(my_pre_delete_callback, sender=MyModel)
post_delete.connect(my_post_delete_callback, sender=MyModel)

Adding Callbacks

Peewee Signal provides four main signals that you can connect your callbacks to:

Let’s see an example of how to define and connect callbacks to these signals:

def my_pre_save_callback(sender, instance, created):
    # Execute custom logic before saving the model instance
    print(f"Pre-save callback triggered for model {sender.__name__}")

def my_post_save_callback(sender, instance, created):
    # Execute custom logic after saving the model instance
    print(f"Post-save callback triggered for model {sender.__name__}")

def my_pre_delete_callback(sender, instance):
    # Execute custom logic before deleting the model instance
    print(f"Pre-delete callback triggered for model {sender.__name__}")

def my_post_delete_callback(sender, instance):
    # Execute custom logic after deleting the model instance
    print(f"Post-delete callback triggered for model {sender.__name__}")

Registering Callbacks

To register the callbacks, we simply need to connect them to the appropriate signals. For example:

pre_save.connect(my_pre_save_callback, sender=MyModel)

You can register multiple callbacks to the same signal, and they will be called in the order they were connected.

Conclusion

Using Peewee Signal in your Python applications can greatly enhance the functionality of your database models. By adding custom callbacks to important events like saving or deleting model instances, you can execute additional logic and perform tasks such as validation, logging, or sending notifications.

Peewee Signal provides an easy and flexible way to extend the capabilities of Peewee ORM. It’s definitely worth exploring if you’re using Peewee in your projects.

Happy coding!