如何从db.event.listens_for中提取“after_insert”(Order,“after_insert”)

时间:2017-07-17 15:56:17

标签: python sqlalchemy

我计划在一个函数上堆叠几个装饰器,并根据操作i在要运行的函数中使用if语句。

@db.event.listens_for(Order, "after_delete")
@db.event.listens_for(Order, "after_insert")
def order_after_delete(mapper, connection, target):
    # find if it was triggered by 'after_delete' or 'after_insert'
    # do stuff...
    if something=='after_insert':
        print('after_insert')
    elif something=='after_delete':
        print('after_insert')

有没有办法从其中一个(mapper, connection, target)获取该信息?

1 个答案:

答案 0 :(得分:0)

你可以检查目标。插入的对象没有身份密钥。

from sqlalchemy import inspect

@db.event.listens_for(Order, "after_delete")
@db.event.listens_for(Order, "after_insert")
def order_after_delete(mapper, connection, target):
    insp = inspect(target)
    if not insp.has_identity:
        print('after_insert')
    else:
        print('after_delete')