Reputation: 4907
I have two callbacks that are triggered on an before_insert
and an before_update
. The code that is executed are the exact same code and what I would like to do is to refactor that so that both @listens_for
execute the same method.
This is what I have:
@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)
This is what I would like (doesn't work btw):
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)
Is there a way of achieving this?
Upvotes: 4
Views: 255
Reputation: 3351
You need to use sqlalchemy.event.listen
function and call it after declaring your change_employee_path
function:
listen(Employee, 'before_insert', change_employee_path)
listen(Employee, 'before_update', change_employee_path)
Upvotes: 1