[파이썬] Peewee 개요

Peewee is a lightweight, expressive Object-Relational Mapping (ORM) library for Python. It provides a simple yet powerful way to interact with databases, allowing developers to focus on their application logic instead of dealing with low-level SQL queries.

Features of Peewee

Peewee offers several key features that make it a popular choice among Python developers:

1. Simplicity: Peewee has a straightforward and intuitive API that is easy to understand and use.

2. Multiple Database Support: Peewee supports various databases such as SQLite, MySQL, PostgreSQL, and others.

3. Models and Relationships: Peewee allows you to define models and create relationships between them, making it easy to represent complex data structures.

4. Querying and CRUD Operations: Peewee provides a powerful query builder that enables you to perform create, read, update, and delete (CRUD) operations on the database.

5. Transactions: Peewee supports transactions, allowing you to bundle multiple database operations into a single atomic unit.

6. Migrations: Peewee offers a built-in migration system that helps you evolve your database schema over time.

Getting Started with Peewee

To get started with Peewee, you need to install it via pip:

pip install peewee

Once installed, you can import Peewee in your Python script or project:

from peewee import *

Example Usage

To demonstrate Peewee’s usage, let’s create a simple User model and perform some CRUD operations:

from peewee import *

# Define the database
db = SqliteDatabase('mydatabase.db')

# Define the User model
class User(Model):
    username = CharField()
    email = CharField()

    class Meta:
        database = db

# Create the tables
db.connect()
db.create_tables([User])

# Create a new user
user = User(username='john_doe', email='john@example.com')
user.save()

# Retrieve all users
users = User.select()

# Update a user's email
user = User.get(User.username == 'john_doe')
user.email = 'john.doe@example.com'
user.save()

# Delete a user
user = User.get(User.username == 'john_doe')
user.delete_instance()

# Close the database connection
db.close()

In the above code, we first import the necessary modules from Peewee and define our User model with its fields. We then create the database tables, create, retrieve, update, and delete users, and finally close the database connection.

Conclusion

Peewee is a flexible and user-friendly ORM for Python, allowing developers to work with databases easily. Its simplicity, multiple database support, relationship management, query builder, and other features make it a valuable tool for building data-driven applications.

To learn more about Peewee and its capabilities, refer to the official documentation. Happy coding!