[파이썬] Peewee Custom Middleware 개발

Peewee is a lightweight and expressive Python ORM (Object-Relational Mapping) library for interacting with SQL databases. It provides a convenient way to work with databases in a Pythonic manner. One of the powerful features of Peewee is the ability to create custom middlewares for database operations.

In this blog post, we will explore how to develop custom middleware in Peewee to add additional functionality to our database interactions.

What is Middleware?

Middleware is a software component that sits between the application and the database. It intercepts the query execution and allows you to modify or enhance the behavior of database operations. With middleware, you can perform tasks such as logging, caching, authentication, or any other operations needed before or after the execution of a query.

Creating a Custom Middleware in Peewee

To create a custom middleware in Peewee, we need to define a class that extends the peewee.DatabaseMiddleware class and overrides its relevant methods. Let’s see a simple example of a middleware that logs the executed queries:

import logging
from peewee import *

class QueryLoggingMiddleware(DatabaseMiddleware):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.logger = logging.getLogger('peewee')
  
    def execute_sql(self, sql, params=None, commit=True):
        self.logger.info(f'Executing query: {sql} with params: {params}')
        return super().execute_sql(sql, params, commit)

In the example above, we create a class called QueryLoggingMiddleware that extends DatabaseMiddleware. We override the execute_sql method to log the executed query along with its parameters using the logging module.

Adding Middleware to Peewee

To use our custom middleware in Peewee, we need to attach it to our Database object. Here’s an example of how to do it:

import logging
from peewee import *

db = SqliteDatabase('mydatabase.db')

# Attach custom middleware
db.middleware(QueryLoggingMiddleware())

# Define Model and perform queries
class User(Model):
    username = CharField()
    email = CharField(unique=True)

    class Meta:
        database = db

# Perform database operations
db.connect()
db.create_tables([User])

# Insert a new user
new_user = User.create(username='john', email='john@example.com')

# Select all users
users = User.select()

# Disconnect from the database
db.close()

In the code above, we first create an instance of our SqliteDatabase. Then, we attach our custom middleware QueryLoggingMiddleware to the database using the middleware() method.

After that, we define our User model and perform some database operations like creating tables, inserting a new user, and selecting all users. Finally, we disconnect from the database.

Conclusion

Peewee’s custom middleware feature allows us to extend the functionality of database operations easily. By creating our own middleware classes, we can add additional functionality to our database interactions, such as logging, caching, or authentication.

In this blog post, we learned how to create a custom middleware in Peewee and how to attach it to a Database object. We also saw a simple example of a middleware that logs executed queries using the logging module.

Feel free to explore Peewee’s documentation for more advanced middleware features and use cases. Happy coding with Peewee!