Python全系列 教程
3567个小节阅读:5929.9k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
对于使用peewee这个模块默认情况下是同步的框架,而在tornado中,需要尽量写异步的操作,用异步的库。因此我们只能考虑下这个peewee库如何才可以异步。
实际自己将peewee改成异步,虽然不难,但还是比较麻烦的。所以可以考虑找下github,看看有没有现成的peewee异步库。
现成的异步peewee库:
github: https://github.com/05bit/peewee-async
PostgreSQL
xxxxxxxxxx
pip install --pre peewee-async; pip install aiopg
MySQL
xxxxxxxxxx
pip install --pre peewee-async; pip install aiomysql
类的创建基本与peewee一样,需要注意的是:
数据的操作,需要注意是的使用异步:
通过 peewee_async.Manager(database) 对象操作数据
增加数据
执行SQL模型
官网案例
xxxxxxxxxx
import asyncio
import peewee
import peewee_async
# Nothing special, just define model and database:
database = peewee_async.PostgresqlDatabase(
database='db_name',
user='user',
host='127.0.0.1',
port='5432',
password='password'
)
class TestModel(peewee.Model):
text = peewee.CharField()
class Meta:
database = database
# Look, sync code is working!
TestModel.create_table(True)
TestModel.create(text="Yo, I can do it sync!")
database.close()
# Create async models manager:
objects = peewee_async.Manager(database)
# No need for sync anymore!
database.set_allow_sync(False)
async def handler():
await objects.create(TestModel, text="Not bad. Watch this, I'm async!")
all_objects = await objects.execute(TestModel.select())
for obj in all_objects:
print(obj.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(handler())
loop.close()
# Clean up, can do it sync again:
with objects.allow_sync():
TestModel.drop_table(True)
# Expected output:
# Yo, I can do it sync!
# Not bad. Watch this, I'm async!
案例代码
xxxxxxxxxx
from models29 import Music,manager
import asyncio
def create_data_by_model():
Music.create(name='我以为我可以一了百了',singer='林志炫',duration='3:10',_type='流行',commany=1)
async def create_data_by_manager():
await manager.create(Music,name='逆战',singer='张杰',duration='2:10',_type='流行',commany=1)
async def query_data_by_manager():
m_list = await manager.execute(Music.select())
for m in m_list:
print(f'{m.id} == {m.name} == {m.singer}')
if __name__ == '__main__':
# create_data_by_model()
loop = asyncio.get_event_loop()
# loop.run_until_complete(create_data_by_manager())
loop.run_until_complete(query_data_by_manager())
实时学习反馈
1. 对于peewee_async模块,使用说法错误的是?
A 需要修改类的database
属性为peewee_async.Manager(database)
B 可以通过Model.creat_table
方法创建表
C 可以通过peewee_async.Manager(database)
对象修改表数据
D 可以通过peewee_async.Manager(database)
对象执行SQL对象
答案
1=>B