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

如何在Flask中正确打印request.endpoint,而非static值?

Flask中before_request打印request.endpoint显示static而非业务路由的解决办法

问题原因

Flask的before_request钩子会拦截所有请求,包括页面引用的CSS/JS这类静态资源请求,而静态请求对应的request.endpoint就是'static'。当你访问业务路由(比如/对应的index)后,浏览器会自动发起静态资源请求,每次请求都会触发before_request;再加上你的代码逻辑是session中无username时就打印当前请求的endpoint,所以就出现了频繁打印static的情况。


解决方案1:仅打印业务路由的endpoint(最常用)

如果你的需求是静态资源正常加载,但只在访问业务路由时打印对应的endpoint,直接在打印逻辑中过滤掉静态请求即可:

修改main.py中的before_request函数:

@app.before_request
def before_request():
    print("before_request")

    # 仅当请求不是静态资源且session中无username时,打印业务路由的endpoint
    if 'username' not in session and request.endpoint != 'static':
        print(request.endpoint) 

这样浏览器请求CSS/JS时不会触发打印,只有访问index、login这类业务路由时,才会输出对应的endpoint,完全不影响静态资源的正常加载。


解决方案2:静态请求时也打印对应业务路由

如果需要静态请求时也打印当前页面的业务路由(比如加载index页面的CSS时,输出index而非static),可以通过session存储最近访问的业务路由,静态请求时复用该值:

修改main.py:

# 先配置session密钥(必须,否则session无法正常使用)
app.secret_key = 'your-custom-secret-key'  # 替换为任意字符串,用于session加密

@app.before_request
def before_request():
    print("before_request")

    if request.endpoint != 'static':
        # 记录当前访问的业务路由到session
        session['current_endpoint'] = request.endpoint
        if 'username' not in session:
            print(request.endpoint)
    else:
        # 静态请求时,打印session中记录的业务路由
        if 'username' not in session:
            print(session.get('current_endpoint', 'unknown'))

这个方案会在你访问业务路由时更新session中的路由记录,后续该页面的静态资源请求都会打印这个业务路由的值。

内容的提问来源于stack exchange,提问作者José García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:53:18