我有两个在before_insert
和before_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)
有没有办法实现这个目标?
答案 0 :(得分:0)
您需要使用sqlalchemy.event.listen
函数并在声明change_employee_path
函数后调用它:
listen(Employee, 'before_insert', change_employee_path)
listen(Employee, 'before_update', change_employee_path)