天问 bf660e7051 Update 'README.md' | 9 months ago | |
---|---|---|
README.md | 9 months ago |
异步ORM(对象关系映射)框架, 类似的有 sqlalchemy,flask-sqlalchemy,alembic
from tortoise.models import Model
from tortoise import fields
from tortoise import Tortoise
class User(Model):
id = fields.IntField(pk=True)
username = fields.CharField(max_length=50)
email = fields.CharField(max_length=50)
class Meta:
table = "users"
async def run():
# 初始化Tortoise
await Tortoise.init(
db_url='sqlite://db.sqlite3',
modules={'models': ['__main__']}
)
# 创建数据库表
await Tortoise.generate_schemas()
# 创建一个新的用户
user = await User.create(username='testuser', email='test@example.com')
# 查询用户
user = await User.get(username='testuser')
print(user.id, user.username, user.email)
# 运行异步函数
import asyncio
asyncio.run(run())