這個問題在這里已經有了答案: 每次訪問 Flask 視圖的增量計數器 2 個答案 5 天前關閉。
所以我正在使用 Flask 創建簡單的網頁,只是為了練習,我有這個小問題。我想計算我重新加載頁面的次數。例如:
count = 0
@app.route("/")
def home():
print(count)
count = 1
return "testing"
但這不起作用。如果你們對此有所了解,請提供幫助。<3 謝謝!
uj5u.com熱心網友回復:
上面的代碼可以作業,但是由于您試圖count從函式訪問變數,因此您需要在函式中宣告它的 a global:
count = 0
@app.route("/")
def home():
global count
print(count)
count = 1
return "testing"
更多關于全域變數的資訊在這里
uj5u.com熱心網友回復:
這不是與燒瓶有關的問題。它與python全域變數有關。您只需要使用該變數訪問在函式內部全域宣告的全域global變數。在此處查看與 python 變數型別相關的更多詳細資訊。
代碼可以更新為
count = 0
@app.route("/")
def home():
global count
print(count)
count = 1
return "testing"
注意:并發用戶的最佳實踐是避免使用該global變數。相反,使用這里提到的 python multiprocessing.Value
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443961.html
