Python的轻量级ORM框架peewee

作者:小小明

在前面的《改变python对象的黑魔法metaclass》一文中,我介绍了使用metaclass自己编写ORM框架的思路。

地址:https://blog.csdn.net/as604049322/article/details/111939998

当然python库中这类框架非常多,我们并没有必要自己去实现。

ORM框架使用最广泛的就是SQLAlchemy和Django自带的ORM框架,但是SQLAlchemy的语法显然相对Django的ORM框架麻烦一点。

而Django本身是一个web框架,比较重量级,仅仅为了使用Django的ORM框架的功能,而安装Django有点导致系统臃肿。而peewee这个框架语法几乎与Django的ORM框架一致,而又非常轻量。

它的安装非常简单:

pip install peewee

如果你在使用mysql数据库的过程中报出如下错误:

peewee.ImproperlyConfigured: MySQL driver not installed!

则需要安装一个mysql的驱动:

pip install pymysql

peewee的whl包是880kB,pymysql的whl包是51KB,非常轻量级。

peewee的官方文档地址:http://docs.peewee-orm.com/en/latest/index.html

下面测试一下各项功能:

from peewee import *

db = MySQLDatabase('test', host="localhost", user='root', passwd='123456', port=3306)


# 定义Person
class Person(Model):
    name = CharField()
    birthday = DateField()
    is_relative = BooleanField()

    class Meta:
        database = db
        
def test_create():
    Person.create_table()
    # 创建多张表也可以这样
    # database.create_tables([Person])


def test_insert():
    # 添加一条数据
    p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=True)
    p.save()


def test_delete():
    # 删除姓名为perter的数据
    Person.delete().where(Person.name == 'perter').execute()
    # 已经实例化的数据, 使用delete_instance
    p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=False)
    p.id = 1
    p.save()
    p.delete_instance()


def test_update():
    # 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
    p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=False)
    p.id = 1
    p.save()

    # 更新birthday数据
    q = Person.update({
     Person.birthday: date(1983, 12, 21)}).where(Person.name == '小华')
    q.execute()


def test_query():
    # 查询单条数据
    p = Person.get(Person.name == '小华')
    print(p.name, p.birthday, p.is_relative)

    # 使用where().get()查询
    p = Person.select().where(Person.name == '小华').get()
    print(p.name, p.birthday, p.is_relative)

    # 查询多条数据
    persons = Person.select().where(Person.is_relative == True)
    for p in persons:
        print(p.name, p.birthday, p.is_relative)

笔者运行每个方法后,均得到了正确的结果。

你可能感兴趣的:(python,sql)