gpt4 book ai didi

python - 如何将我的两个 @listens_for 事件回调重构为一个?

转载 作者:行者123 更新时间:2023-12-05 06:43:12 25 4
gpt4 key购买 nike

我有两个在 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)

有什么办法可以实现吗?

最佳答案

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

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

关于python - 如何将我的两个 @listens_for 事件回调重构为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com