2016-12-05 130 views
0

我試圖通過提交一次又一次地加載表單,直到計數器在n(例如3,參見圖形)。因爲我在python中很新,所以我無法處理for循環和計數器。你有任何建議或想法,我如何能夠正確實施這一點? enter image description herePython中的循環POST方法

非常感謝您提前。

@app.route('/accounts/test/login', methods=['GET', 'POST']) 
def accounts_test_login(): 

if request.method == 'POST': 
    word = request.form['character'] 
    scribble_normalized = pd.DataFrame(normalize(json.loads(request.form['output1']))) 
    saved = load_scribbles_for_user(word) 
    result = similarity(scribble_normalized, saved) 
    session['scores'] = [] 

    if result: 
     sumSessionCounter() 
     session['scores'].extend([word, True]) 
     if session['counter'] >= 5: 
      session['counter'] = 0 
      return render_template('accounts/test/failure.html', word=word, output=scribble_normalized, 
         errors=scores) 
     return render_template('accounts/test/medium.html', word=word, output=scribble_normalized) 


    else: 
     sumSessionCounter() 
     session['scores'].extend([word, False]) 
     if session['counter'] >= 5: 
      session['counter'] = 0 
      return render_template('accounts/test/failure.html', word=word, output=scribble_normalized, 
         errors=session['scores']) 
     return render_template('accounts/test/medium.html', word=word, output=scribble_normalized) 

,這裏是功能sumSessionCounter

def sumSessionCounter(): 
try: 
session['counter'] += 1 
except KeyError: 
session['counter'] = 1 
+1

每次blowser'POST'頁到服務器,然後服務器調用'再次accounts_test_login',並將它設置'計數器= 0'。你必須在'session'或'databas'e中保存'counter'或者在'url'中使用它。 'accounts/test/medium.html?count = some_value'來關注這個值。 – furas

回答

1

由於furas在他的評論所說,你可以存儲在會話或者一個數據庫中的計數器。您也可以將其作爲隱藏輸入字段存儲在表單上。

在模板:

<input type="hidden" name="counter" value="{{ counter }}"> 

在你看來:

counter = request.form.get('counter', type=int) or 0 


return render_template('accounts/test/medium.html', word=word, output=scribble_normalized, counter=counter+1) 
+0

非常感謝Kevin和Furas! 我現在用「session ['counter']更新了我的代碼,它效果更好,一旦它計數到5並返回另一個模板就會停下來。但是現在我遇到了這樣的問題:如果少數人在相同的情況下測試應用程序時間,櫃檯會保持它對於每個人都是一樣的,而不是個人。這不應該是這樣,你有什麼進一步的建議嗎?非常感謝! –

+1

會話值被存儲在一個cookie。這些是特定於每個用戶,所以你不應該遇到這個問題 –

+0

非常感謝凱文,我非常欣賞這一點! 你可能也可以幫我解決我試圖設置的數組(請參閱更新的代碼)。最新的實體,我做錯了,數組應該總是存儲結果並顯示在最後一頁。 –