有没有办法根据 FastAPI 启动事件的条件取消启动?

Is there a way to cancel the start depending on a condition with FastAPI startup event?

我想做的是检查启动事件的条件,如果发生异常,则不要启动服务器或停止服务器。


@app.on_event("startup")
def startup_event():
    public_key = None

    try:
        with open(PUBLIC_KEY_FILE) as public_key_file:
            public_key = public_key_file.read()
    except Exception as f_error:
        logger.exception(f_error)

        # cancel the startup

有办法吗?

在启动函数中引发异常:


@app.on_event("startup")
def startup_event():
    public_key = None

    try:
        with open(PUBLIC_KEY_FILE) as public_key_file:
            public_key = public_key_file.read()
    except Exception as f_error:
        logger.exception(f_error)

        raise SomeException()