我如何计算我在 python Flask 中重新加载页面的次数?

How can i count how many time i've reloaded page in python Flask?

所以我正在使用 Flask 创建简单的网页,只是为了练习,我遇到了这个小问题。 我想数一数我重新加载页面的次数。例如:

count = 0
@app.route("/")
def home():
    print(count)
    count += 1
    return "testing"

但这不起作用。如果你们对此有所了解,请提供帮助。 <3 谢谢!

上面的代码可以工作,但是因为你试图从一个函数访问 count 变量,你需要在函数中声明它是一个 global:

count = 0
@app.route("/")
def home():
    global count
    print(count)
    count += 1
    return "testing"

关于全局变量的更多信息here

这不是烧瓶的问题。它与 python 全局变量有关。您只需要使用 global 变量访问在函数内部全局声明的全局变量。查看 here 以获取与 python 变量类型相关的更多详细信息。

代码可以更新为

count = 0
@app.route("/")
def home():
    global count
    print(count)
    count += 1
    return "testing"

注意:并发用户的最佳做法是避免使用 global 变量。相反,使用 python multiprocessing.Value as mentioned