手把手带你入门Python爬虫(四、ORM与peewee)

一、为什么要用ORM

  • 隔离数据库和数据库版本之间的差异
  • 便于维护
  • ORM会提供防sql注入等功能
  • 变量传递式的调用更加简单
  • ORM越来越流行

二、ORM的选择

框架优点缺点
peeweeDjango式的API,使其易用 轻量实现,很容易和任意web框架集成不支持自动化 schema 迁移 多对多查询写起来不直观
SQLObject采用了易懂的ActiveRecord 模式 ;一个相对较小的代码库方法和类的命名遵循了Java 的小驼峰风格 ;不支持数据库session隔离工作单元
Storm清爽轻量的API,短学习曲线和长期可维护性;不需要特殊的类构造函数,也没有必要的基类迫使程序员手工写表格创建的DDL语句,而不是从模型类自动派生;Storm的贡献者必须把他们的贡献的版权给Canonical公司
Django’s ORM易用,学习曲线短;和Django紧密集合,用Django时使用约定俗成的方法去操作数据库不好处理复杂的查询,强制开发者回到原生SQL;紧密和Django集成,使得在Django环境外很难使用
SQLAlchemy企业级 API,使得代码有健壮性和适应性;灵活的设计,使得能轻松写复杂查询工作单元概念不常见;重量级 API,导致长学习曲线

我们选择peewee这个框架来学习,因为它简单、灵活、申明方式和django的ORM接近。且star数量高,活跃度高,文档质量高。

官方文档:http://docs.peewee-orm.com/en/latest/

三、peewee使用

1. 安装

切换到虚拟环境,然后安装

pip install peewee

2. 创建并使用

from peewee import *

db = MySQLDatabase("py_spider", host="localhost", port=3307, user="root", password="root")


class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db  # This model uses the "people.db" database.


if __name__ == "__main__":
    db.create_tables([Person])  # 根据模型创建数据表

生成的数据表,表名默认为类名,默认会加一个ID字段(主键):
在这里插入图片描述

Field types table(数据库与模型字段对应表)

Field TypeSqlitePostgresqlMySQL
AutoFieldintegerserialinteger
BigAutoFieldintegerbigserialbigint
IntegerFieldintegerintegerinteger
BigIntegerFieldintegerbigintbigint
SmallIntegerFieldintegersmallintsmallint
IdentityFieldnot supportedint identitynot supported
FloatFieldrealrealreal
DoubleFieldrealdouble precisiondouble precision
DecimalFielddecimalnumericnumeric
CharFieldvarcharvarcharvarchar
FixedCharFieldcharcharchar
TextFieldtexttexttext
BlobFieldblobbyteablob
BitFieldintegerbigintbigint
BigBitFieldblobbyteablob
UUIDFieldtextuuidvarchar(40)
BinaryUUIDFieldblobbyteavarbinary(16)
DateTimeFielddatetimetimestampdatetime
DateFielddatedatedate
TimeFieldtimetimetime
TimestampFieldintegerintegerinteger
IPFieldintegerbigintbigint
BooleanFieldintegerbooleanbool
BareFielduntypednot supportednot supported
ForeignKeyFieldintegerintegerinteger

3. 增删查改

(1) 新增

if __name__ == "__main__":
    # db.create_tables([Person])  # 创建数据表
    from datetime import date
    # 生成数据
    bob = Person(name="Bob", birthday=date(2020, 12, 12))
    # 新增数据到数据库
    bob.save()

在这里插入图片描述

(2) 查询数据

if __name__ == "__main__":
    # 只查询一条数据  get方法在取不到数据会抛出异常,需try catch
    Bob = Person.select().where(Person.name == 'Bob').get()
    print(Bob.name)     # Bob
    print(Bob.birthday)     # 2020-12-12
    # 同上
    Bob2 = Person.get(Person.name == 'Bob')
    print(Bob2.name)    # Bob
    print(Bob2.birthday)    # 2020-12-12

    # 查询多条数据
    Bobs = Person.select().where(Person.name == 'Bob')
    for b in Bobs:
        print(b.name)
        print(b.birthday)

(3) 修改数据

if __name__ == "__main__":
    from datetime import date
    # 修改数据
    Bobs = Person.select().where(Person.name == 'Bob')
    for b in Bobs:
        b.birthday = date(1997, 10, 16)
        b.save() # 在没有数据的时候新增,存在的时候修改

在这里插入图片描述

(4) 删除数据

if __name__ == "__main__":
    # 删除数据
    Bobs = Person.select().where(Person.name == 'Bob')
    for b in Bobs:
        b.delete_instance()
        

在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值