python开发小型数据库_python web开发之数据库ORM的 peewee库 动手学习实践笔记
背景
在web開發(fā)的時候,一些比較簡單的小型系統(tǒng)其實也得ORM框架,顯而易見其實開發(fā)速度上是提升很多,因為有必要學(xué)習(xí)一下對應(yīng)的ORM庫。
關(guān)于ORM一些說明
關(guān)于ORM(Object Relational Mapping,對象關(guān)系映射)在python中其實存在幾個,主要有的還有SQLAlchemy,不過其實今天咋們的豬腳peewee的內(nèi)核其實也是基于SQLAlchemy,所以可能應(yīng)該是更加高效!因為還沒做進行具體的測試和數(shù)據(jù)對比,所以現(xiàn)在還是猜測!
后期我也會繼續(xù)實踐一下關(guān)于SQLAlchemy在bottle中的使用!
理論上相關(guān)ORM應(yīng)該具備的能力有:
(1)對象關(guān)系映射(數(shù)據(jù)類型映射,類映射,關(guān)系映射)
(2)CURD操作
(3)緩存優(yōu)化
ORM一些優(yōu)點:
(1)屏蔽數(shù)據(jù)庫操作細節(jié),開發(fā)者不需要通過SQL進行和數(shù)據(jù)庫進行交互,提高開發(fā)效率
(2)便捷數(shù)據(jù)庫遷移
(3)緩存技術(shù)提高數(shù)據(jù)庫操作效率。
安裝
pip install peewee
image.png
示例
因為我這邊的環(huán)境數(shù)據(jù)庫使用的還是Postgresql,所以示例我就以Postgresql為主:
先通過navicat在本地新建一個測試數(shù)據(jù)庫叫做:test_peewee
image.png
新建一個py文件(LearnPeewee.py):
image.png
#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
# ┏┓ ┏┓+ +
# ┏┛┻━━━┛┻┓ + +
# ┃ ┃
# ┃ ━ ┃ ++ + + +
# ████━████ ┃+
# ┃ ┃ +
# ┃ ┻ ┃
# ┃ ┃ + +
# ┗━┓ ┏━┛
# ┃ ┃
# ┃ ┃ + + + +
# ┃ ┃ Codes are far away from bugs with the animal protecting
# ┃ ┃ + 神獸保佑,代碼無bug
# ┃ ┃
# ┃ ┃ +
# ┃ ┗━━━┓ + +
# ┃ ┣┓
# ┃ ┏┛
# ┗┓┓┏━┳┓┏┛ + + + +
# ┃┫┫ ┃┫┫
# ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/3/21 23:11
@version: v1.0.0
@Contact: 308711822@qq.com
@File: LearnPeewee.py
@文件功能描述:
"""
from peewee import *
# 建立一個PostgresqlDatabase數(shù)據(jù)庫引擎對象,連接到本地的數(shù)據(jù)庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", passwd="123456")
db.connect()
# 定義一個ORM基類,在基類中指定本ORM所使用的數(shù)據(jù)庫
class BaseModel(Model):
class Meta:
database = db
# 定義一個Course表(課程表)。繼承于BaseModel
class Course(BaseModel):
id = PrimaryKeyField() # 課程唯一標識
title = CharField(null=False) # 課程名稱
period = IntegerField() # 學(xué)時
des = CharField() # 課程描述
class Meta:
order_by = {'title', }
db_table = 'course' # 定義數(shù)據(jù)庫中表的名稱
# 定義一個Teacher表(老師表)。繼承于BaseModel
class Teacher(BaseModel):
id = PrimaryKeyField() # 唯一標識
name = CharField(null=False) # 名稱
gender = BooleanField() # 性別
address = CharField() # address地址
course_id = ForeignKeyField(Course, to_field='id', related_name='course')
class Meta:
order_by = {'name', }
db_table = 'teacher' # 定義數(shù)據(jù)庫中表的名稱
# 執(zhí)行建表,只需要執(zhí)行一次
Course.create_table()
Teacher.create_table()
執(zhí)行報錯:
image.png
原因是:
連接字段參數(shù)錯誤
passwd--->password
# 建立一個PostgresqlDatabase數(shù)據(jù)庫引擎對象,連接到本地的數(shù)據(jù)庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()
執(zhí)行成功后查看一下對應(yīng)的數(shù)據(jù)庫表的情況:
image.png
代碼:
#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
# ┏┓ ┏┓+ +
# ┏┛┻━━━┛┻┓ + +
# ┃ ┃
# ┃ ━ ┃ ++ + + +
# ████━████ ┃+
# ┃ ┃ +
# ┃ ┻ ┃
# ┃ ┃ + +
# ┗━┓ ┏━┛
# ┃ ┃
# ┃ ┃ + + + +
# ┃ ┃ Codes are far away from bugs with the animal protecting
# ┃ ┃ + 神獸保佑,代碼無bug
# ┃ ┃
# ┃ ┃ +
# ┃ ┗━━━┓ + +
# ┃ ┣┓
# ┃ ┏┛
# ┗┓┓┏━┳┓┏┛ + + + +
# ┃┫┫ ┃┫┫
# ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/3/21 23:11
@version: v1.0.0
@Contact: 308711822@qq.com
@File: LearnPeewee.py
@文件功能描述:
"""
from peewee import *
from playhouse.shortcuts import model_to_dict, dict_to_model
# from playhouse.pool import PooledPostgresqlExtDatabase
#
# db = PooledPostgresqlExtDatabase(
# 'my_database',
# max_connections=8,
# stale_timeout=300,
# user='postgres')
#
# class BaseModel(Model):
# class Meta:
# database = db
# 建立一個PostgresqlDatabase數(shù)據(jù)庫引擎對象,連接到本地的數(shù)據(jù)庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()
# 定義一個ORM基類,在基類中指定本ORM所使用的數(shù)據(jù)庫
class BaseModel(Model):
class Meta:
database = db
# 定義一個Course表(課程表)。繼承于BaseModel
class Course(BaseModel):
id = PrimaryKeyField() # 課程唯一標識
title = CharField(null=False) # 課程名稱
period = IntegerField() # 學(xué)時
des = CharField() # 課程描述
class Meta:
order_by = {'title', }
table_name = 'course' # 定義數(shù)據(jù)庫中表的名稱
# 定義一個Teacher表(老師表)。繼承于BaseModel
class Teacher(BaseModel):
id = PrimaryKeyField() # 唯一標識
name = CharField(null=False) # 名稱
gender = BooleanField() # 性別
address = CharField() # address地址
course_id = ForeignKeyField(Course, to_field='id', related_name='course')
class Meta:
order_by = {'name', }
table_name = 'teacher' # 定義數(shù)據(jù)庫中表的名稱
# 執(zhí)行建表,只需要執(zhí)行一次
Teacher.drop_table()
Course.drop_table()
# peewee.IntegrityError: 錯誤: 在 "course" 上的更新或刪除操作違反了在 "teacher" 上的外鍵約束 "teacher_course_id_fkey"
# DETAIL: 鍵值對(id)=(2)仍然是從表"teacher"引用的.
# 執(zhí)行建表,只需要執(zhí)行一次
# Teacher.delete()
Course.create_table()
Teacher.create_table()
# 新增行
obj1 = Course.create(id=1, title='經(jīng)濟學(xué)', period=320, des='文理科學(xué)生均可選修')
# 把數(shù)據(jù)對象轉(zhuǎn)成字典
u = model_to_dict(obj1)
print(u)
print('通過create()方法添加數(shù)據(jù),它會返回一個模型實例:--->', u)
# 把字典轉(zhuǎn)成數(shù)據(jù)對象
user_data = {'id': 2, 'username': 'charlie'}
obj1 = dict_to_model(Course, u)
print('把字典轉(zhuǎn)成數(shù)據(jù)對象:---->', obj1.title)
Course.create(id=2, title='大學(xué)英語', period=300, des='大一學(xué)生必修課')
Course.create(id=3, title='哲學(xué)', period=100, des='必修課')
Course.create(id=104, title='編譯原理', period=100, des='計算機系選修')
Teacher.create(name='白陣君', gender=True, address='.1.', course_id=1)
Teacher.create(name='李森', gender=True, address='.2.', course_id=3)
Teacher.create(name='張雯雯', gender=False, address='.3.', course_id=2)
Teacher.create(name='李森222', gender=True, address='.344.', course_id=3)
# 查詢一行
record = Course.get(Course.title == '大學(xué)英語')
print("課程:%s, 學(xué)時:%d" % (record.title, record.period))
# 更新
record.period = 200
record.save()
print('更新')
# 刪除
# 查詢一行
record = Course.get(Course.title == '大學(xué)英語')
print("更新之后---課程:%s, 學(xué)時:%d" % (record.title, record.period))
# peewee.IntegrityError: 錯誤: 在 "course" 上的更新或刪除操作違反了在 "teacher" 上的外鍵約束 "teacher_course_id_fkey"
# DETAIL: 鍵值對(id)=(2)仍然是從表"teacher"引用的.
# 這里想要刪除一門課程,但是這門課程可能有一個老師在占用已解決安排上課了!!想要直接刪除課程的話,需要先把占用這門課程的老師給刪除
# get()方法只能查詢一條,且是唯一的一條數(shù)據(jù)
teacher_record = Teacher.get(Teacher.course_id == record.id)
print('老師的記錄', teacher_record.name)
teacher_record.delete_instance()
print('老師被刪除記錄')
print('刪除課程成功!!!')
print('查詢老師!')
# teacher_record = Teacher.get(Teacher.course_id ==record.id)
# for i in teacher_record:
# print(i.name, i.address)
# 查詢所有記錄
courses = Course.select()
for i in courses:
print(i.id, i.title, i.period, i.des)
# 帶條件查詢,并將結(jié)果按period字段倒序排序
courses = Course.select().where(Course.id < 10).order_by(Course.period.desc())
for i in courses:
print(i.id, i.title, i.period, i.des)
# 統(tǒng)計所有課程的平均學(xué)時
total = Course.select(fn.Avg(Course.period).alias('avg_period'))
for i in total:
print(u"平均學(xué)時:", i.avg_period)
# 更新多個記錄
Course.update(period=300).where(Course.id > 100).execute()
# 多表連接操作,Peewee會自動根據(jù)ForeignKeyField的外鍵定義進行連接:
Record = Course.select().join(Teacher).where(Teacher.gender == True)
for i in Record:
print(i.id, i.title, i.period, i.des)
db.close()
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的python开发小型数据库_python web开发之数据库ORM的 peewee库 动手学习实践笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用DOS系统功能调用(INT 21H
- 下一篇: websocket python爬虫_p