[파이썬] Peewee 데이터베이스 연결 설정

Peewee is a simple and lightweight ORM (Object-Relational Mapping) library for Python. It provides a simple and expressive API to interact with databases. In this blog post, we will discuss how to set up and connect to a database using Peewee.

Installing Peewee

Before we start, make sure you have Peewee installed. You can install it using pip, the Python package manager. Open your terminal and run the following command:

pip install peewee

Connecting to a Database

To connect to a database using Peewee, you need to define a database object. The database object represents the connection to your database and is used to execute queries and manage transactions.

Peewee supports multiple database backends such as SQLite, MySQL, PostgreSQL, and more. In this example, we will connect to an SQLite database. Here’s how you can create a database object and connect to an SQLite database:

from peewee import SqliteDatabase

# Create a database object
database = SqliteDatabase('mydatabase.db')

# Connect to the database
database.connect()

Make sure to replace 'mydatabase.db' with the path to your SQLite database file.

Creating Models

After connecting to the database, you can define your models. Models represent the tables in your database and define the structure of your data. Each model class corresponds to a table in the database.

Here’s an example of defining a simple user model using Peewee:

from peewee import Model, CharField

class User(Model):
    username = CharField(max_length=50)
    email = CharField(max_length=100)

    class Meta:
        database = database

In this example, we define a User model with two fields: username and email. The Meta inner class specifies the database to use, which is the database object we created earlier.

Creating Tables

Once you have defined your models, you need to create the corresponding tables in the database. Peewee provides a convenient method called create_tables() that you can use to create all the tables defined in your models.

Here’s an example of how to create the tables:

database.create_tables([User])

In this example, we call the create_tables() method and pass in a list of models that we want to create the tables for. In this case, we only pass in the User model.

Conclusion

In this blog post, we learned how to set up and connect to a database using Peewee. We also saw how to define models to represent tables in the database and how to create those tables. Peewee’s simplicity and easy-to-use API make it a great choice for working with databases in Python.

I hope you found this tutorial helpful. Happy coding!