python / flask:如何在调用另一个函数时 运行 一个函数

python / flask: How to run a function whenever another is called

我有一个函数叫做 when_login()

每当调用 Flask-Login 模块中的 login_user() 函数时,我都需要 运行 它

我无法编辑/重写 login_user() 以调用 when_login() 和程序功能

重写函数也可能导致应用程序变慢

通常:有没有一种方法可以在 python 中绑定函数而不编辑第一个将被调用的函数?

This is for a flask application but I'd be pleased with python-wide answer.

我不确定这是否是您想要的,也许有 Flask 特定的方法可以做到这一点,但这是我尝试过的方法

from flask_login import login_user as login_user__

def run_first(fun):
    def inner(*args):
        fun(*args)
        when_login() # add arguments you want for making this call
    return inner

def when_login(*args):
    print('processing something with args in when_login')

@run_first
def login_user(*args):
    print('login_user is running first')
    return login_user__(*args)

login_user() # call this however you normally use

输出:

login_user is running first
processing something with args in when_login

调用 login_user 使得 运行 首先是 when_login,您可以在打印语句中注意到这一点。

这不需要您更改代码,在开始烧瓶过程之前将其添加到顶层。