python开发小型数据库_python web开发之数据库ORM的 peewee库 动手学习实践笔记
背景
在web開發的時候,一些比較簡單的小型系統其實也得ORM框架,顯而易見其實開發速度上是提升很多,因為有必要學習一下對應的ORM庫。
關于ORM一些說明
關于ORM(Object Relational Mapping,對象關系映射)在python中其實存在幾個,主要有的還有SQLAlchemy,不過其實今天咋們的豬腳peewee的內核其實也是基于SQLAlchemy,所以可能應該是更加高效!因為還沒做進行具體的測試和數據對比,所以現在還是猜測!
后期我也會繼續實踐一下關于SQLAlchemy在bottle中的使用!
理論上相關ORM應該具備的能力有:
(1)對象關系映射(數據類型映射,類映射,關系映射)
(2)CURD操作
(3)緩存優化
ORM一些優點:
(1)屏蔽數據庫操作細節,開發者不需要通過SQL進行和數據庫進行交互,提高開發效率
(2)便捷數據庫遷移
(3)緩存技術提高數據庫操作效率。
安裝
pip install peewee
image.png
示例
因為我這邊的環境數據庫使用的還是Postgresql,所以示例我就以Postgresql為主:
先通過navicat在本地新建一個測試數據庫叫做: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數據庫引擎對象,連接到本地的數據庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", passwd="123456")
db.connect()
# 定義一個ORM基類,在基類中指定本ORM所使用的數據庫
class BaseModel(Model):
class Meta:
database = db
# 定義一個Course表(課程表)。繼承于BaseModel
class Course(BaseModel):
id = PrimaryKeyField() # 課程唯一標識
title = CharField(null=False) # 課程名稱
period = IntegerField() # 學時
des = CharField() # 課程描述
class Meta:
order_by = {'title', }
db_table = 'course' # 定義數據庫中表的名稱
# 定義一個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' # 定義數據庫中表的名稱
# 執行建表,只需要執行一次
Course.create_table()
Teacher.create_table()
執行報錯:
image.png
原因是:
連接字段參數錯誤
passwd--->password
# 建立一個PostgresqlDatabase數據庫引擎對象,連接到本地的數據庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()
執行成功后查看一下對應的數據庫表的情況:
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數據庫引擎對象,連接到本地的數據庫
db = PostgresqlDatabase("test_peewee", host="localhost", port=5432, user="postgres", password="123456")
db.connect()
# 定義一個ORM基類,在基類中指定本ORM所使用的數據庫
class BaseModel(Model):
class Meta:
database = db
# 定義一個Course表(課程表)。繼承于BaseModel
class Course(BaseModel):
id = PrimaryKeyField() # 課程唯一標識
title = CharField(null=False) # 課程名稱
period = IntegerField() # 學時
des = CharField() # 課程描述
class Meta:
order_by = {'title', }
table_name = 'course' # 定義數據庫中表的名稱
# 定義一個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' # 定義數據庫中表的名稱
# 執行建表,只需要執行一次
Teacher.drop_table()
Course.drop_table()
# peewee.IntegrityError: 錯誤: 在 "course" 上的更新或刪除操作違反了在 "teacher" 上的外鍵約束 "teacher_course_id_fkey"
# DETAIL: 鍵值對(id)=(2)仍然是從表"teacher"引用的.
# 執行建表,只需要執行一次
# Teacher.delete()
Course.create_table()
Teacher.create_table()
# 新增行
obj1 = Course.create(id=1, title='經濟學', period=320, des='文理科學生均可選修')
# 把數據對象轉成字典
u = model_to_dict(obj1)
print(u)
print('通過create()方法添加數據,它會返回一個模型實例:--->', u)
# 把字典轉成數據對象
user_data = {'id': 2, 'username': 'charlie'}
obj1 = dict_to_model(Course, u)
print('把字典轉成數據對象:---->', obj1.title)
Course.create(id=2, title='大學英語', period=300, des='大一學生必修課')
Course.create(id=3, title='哲學', 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 == '大學英語')
print("課程:%s, 學時:%d" % (record.title, record.period))
# 更新
record.period = 200
record.save()
print('更新')
# 刪除
# 查詢一行
record = Course.get(Course.title == '大學英語')
print("更新之后---課程:%s, 學時:%d" % (record.title, record.period))
# peewee.IntegrityError: 錯誤: 在 "course" 上的更新或刪除操作違反了在 "teacher" 上的外鍵約束 "teacher_course_id_fkey"
# DETAIL: 鍵值對(id)=(2)仍然是從表"teacher"引用的.
# 這里想要刪除一門課程,但是這門課程可能有一個老師在占用已解決安排上課了!!想要直接刪除課程的話,需要先把占用這門課程的老師給刪除
# get()方法只能查詢一條,且是唯一的一條數據
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)
# 帶條件查詢,并將結果按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)
# 統計所有課程的平均學時
total = Course.select(fn.Avg(Course.period).alias('avg_period'))
for i in total:
print(u"平均學時:", i.avg_period)
# 更新多個記錄
Course.update(period=300).where(Course.id > 100).execute()
# 多表連接操作,Peewee會自動根據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()
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python开发小型数据库_python web开发之数据库ORM的 peewee库 动手学习实践笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用DOS系统功能调用(INT 21H
- 下一篇: 黑马程序员python笔记_三年Pyth