You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask服务器启动运行后执行回调函数?

在Flask 1.1.2中服务器启动后立即打印“Server is running...”的方法

before_first_request只会在第一个请求到达后触发,无法满足你要在服务器启动后立即打印的需求,这里提供两种可靠的实现方式:

方法1:直接调用Werkzeug的run_simple(推荐)

Flask的app.run()底层依赖Werkzeug的run_simple函数,我们可以直接调用这个函数并传入post_start回调——该回调会在服务器成功启动并开始监听端口后执行:

from flask import Flask
from werkzeug.serving import run_simple

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello World'

def on_server_start():
    print("Server is running...")

if __name__ == '__main__':
    run_simple('127.0.0.1', 5000, app, post_start=on_server_start)

方法2:用后台线程异步打印

如果更习惯使用app.run()的调用方式,可以启动一个后台线程,延迟片刻后打印(这种方式依赖短暂等待,适合简单场景):

from flask import Flask
import threading
import time

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello World'

def print_server_status():
    # 短暂等待确保服务器完成启动
    time.sleep(0.5)
    print("Server is running...")

if __name__ == '__main__':
    # 启动守护线程,随主进程自动退出
    threading.Thread(target=print_server_status, daemon=True).start()
    app.run()

注意:方法1是更可靠的官方方案,它直接绑定Werkzeug服务器的启动生命周期,不会因为服务器启动速度慢导致打印时机过早。

内容的提问来源于stack exchange,提问作者hiru007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:07:15