好用的python async orm

46 阅读1分钟

看了很多orm。感觉peewee比较合我心意。但是我还是觉得有些地方不是合我的使用体验。找了很多,最后发现没办法了。自己写,支持3种方式

安装

pip install laorm

方式1 动态查询

直接在模型对象类定义一个方法,上面标注了@sql,不用任何反射。性能压测没有下降。

@table("sys_user")
class User:
    name:str = FieldDescriptor(primary=True)
    id:str = FieldDescriptor()
    @sql
    def selectByAccountAndPassword(a: int, b: str) -> 'List[User]':pass

# 示例调用
user_count:List[User] = User.selectByAccountAndPassword(1,2)
print(user_count)
User.dynamic('selectByAccountAndPassword',[a,b])

方式2 : api链式

User.select("*").where(name="larry").orderby("id").where(id=18).get()
# get(1) 代表主键等于1的数据
Use.select().where('name',1).match('age',18).get(1) 

方式3:直接执行sql

适合简单情况测试。不想定义模型,快速实现,或者复杂sql.

PPA.exec("SELECT * FROM config where id!=1")

下面是其他的crud示例

@table("config")
class Config1:
    id: str = FieldDescriptor(primary=True)
    name: str = FieldDescriptor()

    @sql
    def selectByName(name: str) -> list["Config1"]:
        pass

    # @sql
    # def selectByName(name:str)->'Config1':pass


@router.get("/config2/getdy")
async def getdy():
    res = await Config1.dynamic("selectByIdAndName", [2, 456])
    # res = await Config1.dynamic('selectById',3)
    return {"result": res}


@router.get("/config2/getdy2")
async def getdy2():
    res = await Config1.selectByName(22)
    return {"result": res}


@router.get("/config2/get")
async def get_config2():
    res = await Config1.where(name=22).get()
    return {"result": res}


@router.post("/config2/add")
async def addone():
    await Config1.delete(1)
    await Config1.delete(2)
    config1 = Config1()
    config1.id = 1
    config1.name = 123
    config12 = Config1()
    config12.id = 2
    config12.name = 456
    configlist = [config12]
    await Config1.post(config1)
    await Config1.post(configlist)
    return {"result": "success"}


@router.delete("/config2/delete")
async def deleteone():
    await Config1.delete(1)
    # res = await Config1.where(name=22).delete()
    return {"result": "success"}


@router.delete("/config2/deletedy")
async def deletedy():
    config1 = Config1()
    config1.id = 1
    config1.name = 123
    await Config1.post(config1)
    await Config1.dynamic("deleteById", 1)
    return {"result": "success"}


@router.put("/config2/update")
async def updateone():
    config1 = Config1()
    config1.id = 1
    config1.name = 123
    res = await Config1.where(name=22).update(config1)
    return {"result": res}

压测结果

qps

我的普通4核电脑能跑1000左右

image.png

内存使用

开始压测前

image.png 压测中 image.png