2014-02-18 18 views
0

我有一個表單(它是在index.html中創建的)。 然而,當我點擊提交時,我收到一個400錯誤請求錯誤。我認爲這與在瓶我的應用程序的路線做的,但我不能找出解決的辦法......使用Flask和HTML格式的錯誤請求

index.html中(節選):

<form class="demographic-form" action="/getsurveyresult" method="post">  
    Question:  
    <br>  
    <input type="checkbox" name="question" value="yes">Check this box!  
    <br>  
    <input type="submit" id="submitButton" value="Submit"> 
</form> 

在應用.py:

from flask import * 
import json 

app = Flask(__name__) 
app.debug = True 
app.vars = {} 

@app.route("/") 
def index(): 
    return render_template("index.html") 

@app.route('/getsurveyresults', methods=['POST']) 
def processData(): 
    app.vars['question'] = request.form['question'] 

    f = open('data.txt' ,'w') 
    f.write('question: %s\n' %(app.vars['question'])) 
    f.close() 

    return render_template("getsurveyresults.html") 

if __name__ == "__main__": 
    app.run() 

我在與index.html相同的文件夾中有一個getsurveyresults.html腳本。 Index.html沒有渲染問題。

P.S.我試圖用行動代替行動= 「/ getsurveyresult」= 「{{url_for( 'getsurveyresult')}}」,但我有一個werkzeug.routing.BuildError - 如下圖所示

enter image description here

回答

2

你有兩個問題:

  1. 如果未選中question複選框,然後會出現在POST數據沒有question場。 Flask在argsform(就像普通的Python字典一樣)在無效密鑰查找上產生KeyError的子類。這顯示爲400錯誤。如果字段是可選的使用request.form.get('question')

  2. url_for參數應該是控制器(在這種情況下processData)的名稱,而不是URL。

+0

是的 - 我正在測試它沒有檢查任何框。太棒了!我包含了request.form.get,如果我不輸入任何內容,它不會再拋出錯誤。謝謝! – AllieCat

0

你有一個小錯字:

@app.route('/getsurveyresults') 

<form class="demographic-form" action="/getsurveyresult" 

您需要更改@ app.route到/ getsurveyresult(不含最終S),或改變形式的行動/ getsurveyresultS(與最後S)。您還可以使用燒瓶的url_for功能:

<form class="demographic-form" action="{{ url_for('processData') }}" 
+0

這會導致404 Not Found錯誤。 –

+0

當您使用'url_for()'時,參數應該是視圖方法名稱而不是URL。看到肖恩的答案。 – IanAuld

+0

像IanAuld指出的那樣,URL_FOR應該指向函數名稱,我修改了我的答案。 – binaryatrocity