tornado + peewee 下打印执行 SQL 日志
起步
最近在用 tornado + peewee + peewee-async 写自己的东西。有了早前工作上的重大教训,这次我一上手就着手打开 peewee 或者是 peewee-async 的 SQL 执行日志,遇到了点问题。最后问题解决了,但过程中产生的几个“为什么”想在这里记录一下。
环境准备
Python3.7, tornado6.1, peewee3.14.4, peewee-async0.7.1。
测试代码如下:
from abc import ABC
import tornado.ioloop
import tornado.web
import tornado.log
import peewee
import peewee_async
# ## init peewee async
db = peewee_async.PooledMySQLDatabase(
"test",
user="root", password="123456",
host="guan.com", port=3306,
max_connections=10,
)
db.set_allow_sync(True)
objects = peewee_async.Manager(db)
# ## Student Model
class Student(peewee.Model):
id = peewee.PrimaryKeyField()
name = peewee.CharField()
class Meta:
database = db
# ## http handler
class StudentHandler(tornado.web.RequestHandler, ABC):
async def get(self):
"""
查询学生
cmd: http GET :8080
"""
students = await objects.execute(Student.select())
await self.finish(",".join(s.name for s in students))
async def post(self):
"""
创建一个学生
cmd: http --form POST :8080 name=zhong
"""
Student.create_table(True) # auto create table
name = self.get_body_argument("name")
await objects.create(Student, name=name)
await self.finish("创建成功")
if __name__ == "__main__":
app = tornado.web