Sanic十七:Sanic + 异步orm之Tortoise-ORM

 

Tortoise-ORM 也是个非常优秀的异步orm框架

官网:https://tortoise-orm.readthedocs.io/en/latest/

官网提供的与sanic结合使用的示例:https://tortoise-orm.readthedocs.io/en/latest/examples/sanic.html

 

安装:pip install tortoise-orm

 

模型

 

与app绑定

 

创建用户

 

查询

 

tortoise-orm 要比 SQLALchemy 轻很多,使用也方便很多

 

models

from tortoise import Model, fields


class Users(Model):
id = fields.IntField(pk=True)
name = fields.CharField(50)
age = fields.IntField()

def __str__(self):
return f"User {self.id}: {self.name}: {self.age}"

 

main

import logging

from models import Users
from sanic import Sanic, response

from tortoise.contrib.sanic import register_tortoise

logging.basicConfig(level=logging.DEBUG)

app = Sanic(__name__)


@app.get("/user")
async def list_all(request):
users = await Users.all()
return response.json({"users": [str(user) for user in users]})


@app.post("/user")
async def add_user(request):
user = await Users.create(**request.json)
return response.json({"user": str(user)})


register_tortoise(
app, db_url="mysql://root:123456@localhost/test", modules={"models": ["models"]}, generate_schemas=True
)

if __name__ == '__main__':
import uvicorn

uvicorn.run('main:app', host='0.0.0.0', port=8000, debug=True)

 

posted @ 2021-08-11 22:12  向前走。  阅读(1680)  评论(0编辑  收藏  举报