[파이썬] Peewee 예제 프로젝트 및 tutorials

Peewee is a lightweight and expressive Object Relational Mapping (ORM) library for Python. It allows you to interact with a variety of databases using a simple and intuitive API. In this blog post, we will walk through some example projects and tutorials to help you get started with Peewee.

Setting up Peewee

Before we dive into the examples, let’s quickly cover how to set up Peewee in your Python environment. You can install Peewee using pip:

pip install peewee

Once installed, you can import the library in your Python script as follows:

import peewee

Example Project: To-Do List

To demonstrate the power and simplicity of Peewee, we will create a simple to-do list application. The application will allow users to create, update, and delete tasks. Each task will have a title and a status (completed or not).

Creating the Database

First, we need to create the database and define the schema for our to-do list. Peewee supports various database engines such as SQLite, MySQL, and PostgreSQL. Here’s an example using SQLite:

from peewee import *

db = SqliteDatabase('todo.db')

class Task(Model):
    title = CharField()
    completed = BooleanField(default=False)

    class Meta:
        database = db

db.create_tables([Task])

Adding Tasks

To add tasks to our to-do list, we can use the following code:

task = Task(title="Buy groceries")
task.save()

task = Task(title="Call mom")
task.save()

Updating Tasks

To update the status of a task, we can use the update() method:

task = Task.get(Task.id == 1)
task.completed = True
task.save()

Deleting Tasks

To delete a task, we can use the delete_instance() method:

task = Task.get(Task.id == 2)
task.delete_instance()

Retrieving Tasks

To retrieve all tasks, we can use the select() method:

tasks = Task.select()
for task in tasks:
    print(task.title)

Conclusion

In this blog post, we explored the basics of using Peewee to create a to-do list application. We learned how to set up the database, add, update, delete, and retrieve tasks using Peewee’s intuitive API. Peewee’s simplicity and flexibility make it an excellent choice for Python developers who need a lightweight ORM library.

Remember to consult Peewee’s official documentation for more details and advanced usage. Happy coding!