簡體   English   中英

單擊 flask 應用程序中的按鈕時出現內部服務器錯誤

[英]Internal server error when clicking button in flask app

我是 Flask 的新手,並嘗試構建我的第一個簡單應用程序,該應用程序接受文本輸入,並且在用戶單擊按鈕時,我希望它顯示輸入的文本。

我的 HTML 頁面加載成功,我可以在輸入中輸入文本。 但是,當我單擊按鈕時,我得到一個顯示以下錯誤的新頁面:

Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

我的 HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h1>Predict Code</h1>

            <form action="http://localhost:5000/predict" method="post">
                <label form="description">Description:</label>
                <input type="text" id="description" name="description">
                <button type="submit">Predict Code</button>

            </form>
            <br>
            <br>
            {{ prediction_text }}

    </body>
</html>

我的 flask app.py:

from flask import Flask, request, jsonify, render_template

# create the flask app
app = Flask(__name__)

# what html should be loaded as the home page when the app loads?
@app.route('/')
def home():
    return render_template('app_frontend.html')

# define the logic for reading the inputs from the WEB PAGE, 
# running the model, and displaying the prediction
@app.route('/predict', methods=['GET','POST'])
def predict():

    # get the description submitted on the web page
    a_description = request.form.values()
    return render_template('Description entered: {}'.format(a_description))

# boilerplate flask app code
if __name__ == "__main__":
    app.run(debug=True)

我做錯了什么,我該如何解決?

問題在這里:

@app.route('/predict', methods=['GET','POST'])
def predict():

    # get the description submitted on the web page
    a_description = request.form.values()
    # THIS LINE:
    return render_template('Description entered: {}'.format(a_description)) 

您正在嘗試渲染模板,但傳入的是字符串,而不是模板。

如果您只想返回字符串,請執行以下操作:

return 'Description entered: {}'.format(a_description)

如果您查看 python 錯誤 output 您將看到:

jinja2.exceptions.TemplateNotFound:輸入的描述:<generator object MultiDict.values at 0x000001CEEEF83620>

編輯

回答附加評論問題。 要獲取表單帖子的值,您需要將行從以下位置更改:

a_description = request.form.values()

至:

a_description = request.form.get('description')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM