跳至内容

子类型回调覆盖

在创建 Typer 应用程序时,您可以定义一个回调函数,它始终执行并定义在命令之前出现的 CLI 参数CLI 选项

在另一个应用程序中添加 Typer 应用程序时,子 Typer 也可以有自己的回调。

它可以处理任何在它自己的命令之前出现的 CLI 参数 并执行任何额外的代码

import typer

app = typer.Typer()

users_app = typer.Typer()
app.add_typer(users_app, name="users")


@users_app.callback()
def users_callback():
    print("Running a users command")


@users_app.command()
def create(name: str):
    print(f"Creating user: {name}")


if __name__ == "__main__":
    app()

在本例中,它没有定义任何CLI 参数,只是写入一条消息。

检查它

$ python main.py users create Camila

// Notice the first message is not created by the command function but by the callback
Running a users command
Creating user: Camila

在创建时添加回调

也可以在创建typer.Typer()应用程序时添加回调,该应用程序将被添加到另一个 Typer 应用程序中。

import typer

app = typer.Typer()


def users_callback():
    print("Running a users command")


users_app = typer.Typer(callback=users_callback)
app.add_typer(users_app, name="users")


@users_app.command()
def create(name: str):
    print(f"Creating user: {name}")


if __name__ == "__main__":
    app()

这与上面完全相同,只是添加回调的另一个位置。

检查它

$ python main.py users create Camila

Running a users command
Creating user: Camila

覆盖创建时的回调

如果在创建typer.Typer()应用程序时添加了回调,则可以使用@app.callback()用新的回调覆盖它。

这与您在有关命令 - Typer 回调部分中看到的信息相同,并且适用于子 Typer 应用程序。

import typer

app = typer.Typer()


def default_callback():
    print("Running a users command")


users_app = typer.Typer(callback=default_callback)
app.add_typer(users_app, name="users")


@users_app.callback()
def user_callback():
    print("Callback override, running users command")


@users_app.command()
def create(name: str):
    print(f"Creating user: {name}")


if __name__ == "__main__":
    app()

这里我们在创建typer.Typer()子应用程序时定义了一个回调,但随后我们使用函数user_callback()用新的回调覆盖它。

由于@app.callback()优先于typer.Typer(callback=some_function),因此我们的 CLI 应用程序现在将使用此新的回调。

检查它

$ python main.py users create Camila

// Notice the message from the new callback
Callback override, running users command
Creating user: Camila

在添加子 Typer 时覆盖回调

最后,您可以使用app.add_typer()callback参数,在添加子 Typer 时覆盖在其他任何地方定义的回调。

这具有最高优先级

import typer

app = typer.Typer()


def default_callback():
    print("Running a users command")


users_app = typer.Typer(callback=default_callback)


def callback_for_add_typer():
    print("I have the high land! Running users command")


app.add_typer(users_app, name="users", callback=callback_for_add_typer)


@users_app.callback()
def user_callback():
    print("Callback override, running users command")


@users_app.command()
def create(name: str):
    print(f"Creating user: {name}")


if __name__ == "__main__":
    app()

请注意,优先级属于app.add_typer(),不受执行顺序的影响。下面定义了另一个回调,但app.add_typer()中的回调获胜。

现在,当您使用 CLI 程序时,它将使用新的回调函数callback_for_add_typer()

检查它

$ python users create Camila

// Notice the message from the callback added in add_typer()
I have the high land! Running users command
Creating user: Camila