简介
数据库操作是现代编程中不可或缺的一部分。Python拥有众多ORM库,可以方便地与SQL数据库交互。其中,Peewee以其简洁和轻量著称,非常适合小型项目、脚本甚至微服务。
Peewee这款轻量级ORM提供了模型定义、查询执行、事务处理以及与Web框架集成所需的一切功能,同时易于学习和部署。
ORM工作原理与Peewee的定位
什么是ORM
ORM(对象关系映射)是一种通过编程语言对象操作数据库的技术。您无需编写SQL查询,只需创建和操作Python类,ORM会自动将其转换为SQL语句。
ORM提供了对SQL的抽象,使代码更易读且不易出错。使用ORM的主要优势包括:
- 自动生成SQL查询
- 防止SQL注入攻击
- 轻松切换不同数据库系统
- 与Python对象无缝协作
何时选择Peewee
Peewee在以下场景中表现出色:
- 需要简单轻量的工具
- 项目规模较小或处于实验阶段
- 追求快速开发,无需复杂配置
- 原型开发和小型Web应用
- 使用本地数据库的桌面应用
安装与基本配置
安装Peewee
通过pip即可安装Peewee:
pip install peewee
如需使用不同数据库,还需安装额外包:
# 用于PostgreSQL
pip install psycopg2-binary
# 用于MySQL
pip install PyMySQL
# 用于SQLite(Python内置)
# 无需额外安装
连接数据库
Peewee支持多种数据库类型:
from peewee import SqliteDatabase, PostgresqlDatabase, MySQLDatabase
# SQLite
db = SqliteDatabase('my_database.db')
# PostgreSQL
db = PostgresqlDatabase('mydb', user='username', password='password', host='localhost', port=5432)
# MySQL
db = MySQLDatabase('mydb', user='username', password='password', host='localhost', port=3306)
创建数据模型
基础模型
from peewee import Model, CharField, DateField, IntegerField, TextField
class BaseModel(Model):
class Meta:
database = db
class Author(BaseModel):
name = CharField(max_length=100)
birth_date = DateField()
bio = TextField(null=True)
class Book(BaseModel):
title = CharField(max_length=200)
isbn = CharField(max_length=13, unique=True)
pages = IntegerField()
publication_year = IntegerField()
author = ForeignKeyField(Author, backref='books')
创建表
db.connect()
db.create_tables([Author, Book])
Peewee字段类型
常用字段类型
| 字段类型 | 说明 | 参数 |
|---|---|---|
| CharField | 定长字符串 | max_length, unique, null |
| TextField | 不定长文本 | null |
| IntegerField | 整数 | null, unique |
| FloatField | 浮点数 | null, unique |
| BooleanField | 布尔值 | null, default |
| DateField | 日期 | null, default |
| DateTimeField | 日期时间 |