2017-07-16 35 views
0

我正在使用Python Flask來託管主要工作的Web服務器。我理解這個問題,但我不知道如何解決這個問題。我知道在顯示的代碼中,當網站首次啓動時會渲染模板,變量「CurtainCloseTime」沒有賦值。所以我在我的網站上有兩種形式,我輸入窗簾來關閉和打開變量名稱。變量「CCT」意味着CurtainCloseTime,它是HTML文件中的變量,因爲我希望它顯示回網頁。Python中的Flask&HTML Local變量(UnboundLocalError)

這裏是Python瓶代碼:

@app.route('/', methods=['GET','POST']) 
def index(): 
    if request.method == 'POST': #If there is an input from form 
     CurtainOpenTime = request.form['CurtainOpenTime'] #Assign CurtainOpenTime variable in python to the html CurtainOpenTime variable. 
     CurtainCloseTime = request.form['CurtainCloseTime'] #Assign CurtainCloseTime variable in python to the html CurtainCloseTime variable. 

    return render_template('Index.html', CCT=CurtainCloseTime) 
+0

那麼當'request.method'是** not **設置爲''POST''時會發生什麼?在這種情況下應該呈現什麼? –

+0

我修復了縮進,這是因爲我不得不重寫代碼而不是複製和粘貼。當我設置request.method =='GET'所以不POST,我得到400錯誤的請求錯誤。 – ThePGT

+0

我並沒有建議你改變測試,我要求你考慮GET應該怎麼做。當您收到「POST」方法請求時,變量'CurtainCloseTime'僅爲* set *。你得到這個錯誤是因爲你沒有把它設置在'GET'的情況下。 –

回答

0

首先,我認爲你必須在你的問題的缺口問題。我想,你的實際代碼是:

@app.route('/', methods=['GET','POST']) 
def index(): 
    if request.method == 'POST': #If there is an input from form 
     CurtainOpenTime = request.form['CurtainOpenTime'] # CurtainOpenTime variable in python to the html CurtainOpenTime variable. 
     CurtainCloseTime = request.form['CurtainCloseTime'] #Assign CurtainCloseTime variable in python to the html CurtainCloseTime variable. 

    return render_template('Index.html', CCT=CurtainCloseTime) 

如果這是你的代碼(但是我們不能確定),然後如果HTTP方法是「GET」,CCT沒有價值。你必須在'if'聲明之外指定它:

@app.route('/', methods=['GET','POST']) 
def index(): 
    CurtainCloseTime = # define a default value here 

    if request.method == 'POST': #If there is an input from form 
     CurtainOpenTime = request.form['CurtainOpenTime'] # CurtainOpenTime variable in python to the html CurtainOpenTime variable. 
     CurtainCloseTime = request.form['CurtainCloseTime'] #Assign CurtainCloseTime variable in python to the html CurtainCloseTime variable. 

    return render_template('Index.html', CCT=CurtainCloseTime) 
+0

對不起,您所發佈的縮進是正確的,我不得不將我的Raspberry pi中的代碼重新寫入我用來發布此文件的其他計算機。那麼我怎麼去分配CCT的request.method if語句之外的值呢? – ThePGT

+0

就像我寫第二塊代碼一樣。在'如果'之前(或之後)。因此,如果使用'GET'方法調用路由,'if'之外的所有內容都將被執行,並且在調用'POST'方法時(通常使用表單),將執行'if'內的所有內容。 – leir

相關問題