我怎样才能将我的两个@listens_for事件回调重构为一个?

时间:2015-12-04 16:09:08

标签: python sqlalchemy flask-sqlalchemy

我有两个在before_insertbefore_update上触发的回调。执行的代码是完全相同的代码,我想要做的是重构,以便@listens_for执行相同的方法。

这就是我所拥有的:

@listens_for(Employee, 'before_insert')
def change_employee_path(mapper, connection, target):
    if target.path:
        os.rename(os.path.join(app.config['UPLOAD_FOLDER'], target.path), 'static/images/' + remove_blackduck_address(target.email))
        target.path = remove_blackduck_address(target.email)

@listens_for(Employee, 'before_update')
def change_employee_path(mapper, connection, target):
    if target.path:
        os.rename(os.path.join(app.config['UPLOAD_FOLDER'], target.path), 'static/images/' + remove_blackduck_address(target.email))
        target.path = remove_blackduck_address(target.email)

这就是我想要的(不起作用):

def change_employee_path(mapper,connection, target):
    if target.path:
        os.rename(os.path.join(app.config['UPLOAD_FOLDER'], target.path), 'static/images/' + remove_blackduck_address(target.email))
        target.path = remove_blackduck_address(target.email)

@listens_for(Employee, 'before_insert')
change_employee_path(mapper, connection, target)

@listens_for(Employee, 'before_update')
change_employee_path(mapper, connection, target)

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

您需要使用sqlalchemy.event.listen函数并在声明change_employee_path函数后调用它:

listen(Employee, 'before_insert', change_employee_path)
listen(Employee, 'before_update', change_employee_path)