1.peewee-async是一个为peewee ORM 提供由asyncio支持的异步io库,在单独使用peewee连接池连接时,同时使用到了async和await协程,这样操作会阻塞整个进程,因为tornado是单进程,必须数据库也使用使用异步,才能不阻塞整个进程,这时候就使用到了peewee-async 2.peewee-async就像是django式的API,使其易用,轻量实现,在我们使用tornado中 可以很容易的连接 3.peewee-async通过MySQLDatabase连接数据库,当连接后可以对数据库进行操作也就是orm操作。使用orm操作时 可以隔离数据库之间的差异 方便于维护
pip install peewee
pip install peewee-async
1.创建连接
在项目目录下新建settings.py
import peewee_async
database = peewee_async.MySQLDatabase("usertest", "127.0.0.1", port=3306, user="root", password="mysql")
2.在创建app时配制
from settings import database
from peewee_async import Manager
def getapp():
app = tornado.web.Application([
],**settings)
# 就在这里添加数据库连接
objects = Manager(database)
# 禁止使用同步操作
database.set_allow_sync(False)
app.objects = objects
return app
3.在项目目录下创建models文件夹,用于存放所有的模型类
4.在models下新建base.py
from datetime import datetime
from peewee import Model, DateTimeField
from settings import database
class BaseModel(Model):
create_time = DateTimeField(default=datetime.now, verbose_name="创建时间")
class Meta:
database = database
5.创建项目中需要的表
在models下新建user.py一对多
from peewee import CharField, IntegerField, TextField,ForeignKeyField
from models.base import BaseModel
class Student(BaseModel):
name = CharField(max_length=100, null=False, verbose_name="学生名")
age = IntegerField(null=False, verbose_name="年龄")
desc = TextField(verbose_name="个人简介")
teacher = ForeignKeyField(Teacher, related_name="students")
class Teacher(BaseModel):
name = CharField(max_length=100, null=False, verbose_name="老师名")
age = IntegerField(null=False, verbose_name="年龄")
subject = CharField(max_length=100, null=False, verbose_name="学科")
6.在项目目录下新建init_db.py
from settings import database
from models.user import *
def init_db():
database.create_tables([Teacher, Teacher])
database.create_tables([Student, Student])
if __name__ == '__main__':
init_db()
7.添加、查询、修改、删除数据单表
from datetime import datetime
from .base import BaseHandler
from models.user import *
import json
class TeacherHandler(BaseHandler):
#添加
async def post(self):
# data = json.loads(self.request.body)
teacher = {"name":'zs','age':1,'subject':'234'}
await self.application.objects.create(Teacher,**teacher)
self.write({"code":200})
#修改
async def put(self):
t = Teacher(id=1,name='234')
await self.application.objects.update(t)
self.write({"code":200})
#删除
async def delete(self):
t = Teacher(id=1)
await self.application.objects.delete(t)
self.write({"code":200})
#查询
async def get(self):
#查询单表
teacher = await self.application.objects.get(Teacher,id=2)
create_time = datetime.strftime(teacher.create_time,"%Y-%m-%d %H:%m:%s")
t ={'id':teacher.id,'name':teacher.name,'addtime':create_time}
self.write({"code":200,'tea':t})
8.一对多查询数据
9.多对多
10.条件查询
# 查询所有
teacher = await self.application.objects.execute(Teacher.select())
for i in teacher:
print(i.id)
#查询一条,注意使用get时如果没有数据会报错
teacher = await self.application.objects.get(Teacher,id=2)
print(teacher.id)
#条件查询,返回一条数据也是列表(==,>,<),in
teacher = await self.application.objects.execute(Teacher.select().where(Teacher.id>1).limit(1).offset(0))
for i in teacher:
print(i.name)
# 多个条件查询
where_query=tuple()
where_query+=Teacher.id==2,
where_query+=Teacher.name=='zs',
teacher = await self.application.objects.execute(Teacher.select().where(*where_query))
for i in teacher:
print(i.id)
11.字段初始化参数
1、字段初始化参数 所有字段类型接受的参数及其默认值
null = False 允许空值
index = False 创建索引
unique = False 创建唯一索引
column_name = None 显式指定数据库中的列名
default = None 默认值,可以使任意值或可调用对象
primary_key = False 指明主键
constraints = None 约束条件
sequence = None 序列名字(如果数据库支持)
collation = None 排序字段
unindexed = False 虚表上的字段不应该被索引
choices = None 两种可选项:value display
help_text = None 帮助说明字段。表示此字段的任何有用文本的字符串
verbose_name = None 表示此字段的用户友好名称的字符串
index_type = None 索引类型