其他分享
首页 > 其他分享> > Sanic二十一:Sanic + tortoise-orm 之模型定义

Sanic二十一:Sanic + tortoise-orm 之模型定义

作者:互联网

 

Tortoise ORM 是异步的ORM,设计灵感来自 Django,官网:https://tortoise.github.io/

 

Tortoise ORM 目前支持以下数据库 :
  1、PostgreSQL >= 9.4,使用asyncpg
  2、SQLite,使用aiosqlite
  3、MySQL/MariaDB,使用aiomysql或asyncmy

 

此时的最新版本:0.17.6

 

要求:python版本  >= 3.7

安装:pip install tortoise-orm

 

使用示例:

定义模型:需从tortoise引入Model类,然后所有模型都继承于Model即可,然后引入fields,fields模块提供了非常多的数据类型提供使用

 

然后使用官方提供的 register_tortoise 绑定 sanic 的实例 app 即可

 

register_tortoise 支持的参数

 

app: Sanic实例
config: 字典格式的配置
config_file: 配置文件路径
db_url: 数据库连接信息
modules: 指定模型所在的py文件,放在list中
generate_schemas: 为True则立即生成表信息

config示例:

{
'connections': {
# Dict format for connection
'default': {
'engine': 'tortoise.backends.asyncpg',
'credentials': {
'host': 'localhost',
'port': '5432',
'user': 'tortoise',
'password': 'qwerty123',
'database': 'test',
}
},
# Using a DB_URL string
'default': 'postgres://postgres:qwerty123@localhost:5432/events'
},
'apps': {
'models': {
'models': ['__main__'],
# If no default_connection specified, defaults to 'default'
'default_connection': 'default',
}
}
}

 

标签:tortoise,default,ORM,connection,orm,Sanic,config
来源: https://www.cnblogs.com/zhongyehai/p/15178002.html