python3異步編程,異步orm之 tortoise-orm

前言:

去年下半年爲了做了個web服務,使用了基於python3.5+的一個異步框架 sanic。

其中需要一個異步的mysql引擎,我們常見的也就是 aiomysql,爲了便於開發,我找了一個基於 aiomysql 的簡單封裝的異步引擎 SanicDB,事先說明這個不是orm, 然後到今年因爲業務越來越多,使用 SanicDB 感覺也是很不方便,還導致代碼不夠清晰,然後我又發現了一個新的,真正的 異步orm 引擎  tortoise-orm,經過簡單測試後感覺這個是真的很棒,所以我就棄 SanicDB 而選擇 tortoise-orm。

先來簡單說一下 SanicDB 吧,

源碼很簡單,一共140多行代碼,提供6個對mysql操作的方法,如下圖:

其中 query,get,execute 三個方法是需要傳入原生的 mysql 語句和需要格式化的值,像下面這樣:
|
嗯,還是比較不方便的,但是比直接用 aiomysql 要好一點,好了,我這樣是不好的,用着人家的東西吐槽,嗯,我的錯。
再詳細的可以直接看人家的博客 和git倉庫。

 

現在來詳細介紹一下  tortoise-orm,這是一個真正的異步orm,需要python版本在 3.7 及以上,tortoise-orm支持 SQLite ,PostgreSQL ,MySQL 三種數據庫,
在安裝完  tortoise-orm 之後,你可以選擇安裝 asyncpg aiosqlite aiomysql 三個引擎。

其中 SQLite 對應 aiosqlite ,PostgreSQL  對應 asyncpg ,Mysql 對應 aiomysql。

實例化:

    from tortoise import Tortoise
    import asyncio
    async def init():
        user = 'root'
        password = '123456'
        db_name = 'test'
        await Tortoise.init(
            #指定mysql信息
            db_url=f'mysql://{user}:{password}@127.0.0.1:3306/{db_name}',
            #指定models
            modules={'models': ['sanic_bp.models']}
        )
        #按照模型生成表
        # await Tortoise.generate_schemas()
    asyncio.run(init())

 

在sanic中使用:

本來我是這樣子做的,如下,在 sanic 提供的 after_server_start 監聽器中進行連接,

from sanic import Sanic
from tortoise import Tortoise

app = Sanic(__name__)

@app.listener('after_server_start')
async def notify_server_started(app, loop):
    print('sanic sanic服務啓動後建立mysql連接')
    #實例化mysql連接
    await Tortoise.init(
        db_url='mysql://root:[email protected]:3306/test?maxsize=50&minsize=3',
        modules={'models': ['sanic_bp.models']}
    )

然而,昨天晚上又把 tortoise-orm 的文檔翻了一下,發現人家已經提供方法了,並且在服務退出的時候還會自動關閉 connections,如下,這是 tortoise-orm 提供的demo,我截取了部分,


from tortoise.contrib.sanic import register_tortoise

register_tortoise(
    app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True
)

還有在 fastapi 中的使用方法,都可以在文檔中找到,文檔鏈接我放到此文章最下面了,裏面還有一些其它騷操作。

比如,如果在 Django 中想要在一個app項目中同時使用兩個庫的話很麻煩,要改很多很多操作,而在 sanic 和 fastapi中使用

tortoise-orm 連接多個庫的話就很方便了,像這樣,我又是截取了部分(文抄公),

async def run():
    await Tortoise.init(
        {    
            #這裏面指定兩個不同的數據庫,雖然它填寫的都是一樣的
            "connections": {
                "first": {
                    "engine": "tortoise.backends.sqlite",
                    "credentials": {"file_path": "example.sqlite3"},
                },
                "second": {
                    "engine": "tortoise.backends.sqlite",
                    "credentials": {"file_path": "example1.sqlite3"},
                },
            },
            #可以指定多個不同的models, 嗯,它指定的也是一樣的
            "apps": {
                "tournaments": {"models": ["__main__"], "default_connection": "first"},
                "events": {"models": ["__main__"], "default_connection": "second"},
            },
        }
    )
    #await Tortoise.generate_schemas()
    #選取數據庫
    client = Tortoise.get_connection("first")
    #選取 models
    second_client = Tortoise.get_connection("second")
    #然後這下面就可以進行orm操作了
    


另外:

models指定真實表名方法和django自帶orm稍微有點區別:

django自帶orm:

class Meta:
        db_table = "{table_name}"

tortoise-orm:

    class Meta:
        table = "{table_name}"

至於增刪改查和正常orm操作區別很小,這裏就不敘述了。

 

SanicDB github地址 :https://github.com/veelion/sanicdb   , 博客地址:https://msd.misuland.com/pd/3053059875815821102 
tortoise-orm github地址: https://github.com/tortoise/tortoise-orm ,

tortoise-orm 文檔地址:https://tortoise-orm.readthedocs.io/en/latest/index.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章