【问题标题】:Can not handle python Flask redirected() 'POST' method无法处理 python Flask redirected() 'POST' 方法
【发布时间】:2017-04-20 13:04:17
【问题描述】:

基本上,我为我的 Flask 网页写了两个视图:

@app.route("/")
def main():

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

后来,我以类比的方式创建了另外两个视图:

@app.route("/questions")
def questions():

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

不知何故,我最后的['POST'] 方法根本不起作用。谁能告诉我为什么? (发送第二个['POST'] 后出现“错误请求”。)

这是我的代码:

@app.route("/")
def main():
    questionPath, answersPath, returnPath, databasePath, testName, amount = setup.setup()
    names = database.getListOfTests(databasePath)
    return render_template('index.html', entries = names)

@app.route('/', methods=['POST'])
def main_post():
    text = request.form['text']
    processed_text = text
    questionPath, answersPath, returnPath, databasePath, testName, amount = setup.setup()
    names = database.getListOfTests(databasePath)
    if not text in names:
        return render_template('index.html', entries = names)
    else:
        questions2, answers2 = database.getFromDatabase(processed_text,databasePath)
        session['messages'] = questions2
        return redirect(url_for('questions'))

@app.route("/questions")
def questions():
    messages = session['messages']
    session['messages'] = messages
    return render_template('index2.html', entries = messages)

@app.route('/questions', methods=['POST'])
def questions_post():
    text2 = request.form['text2']
    processed_text = text2
    print(processed_text)
    return "XD"

还有html:

index.html

<form action="." method="POST">
    <input type="text" name="text">
    <input type="submit" name="my-form" value="Send">
</form>

index2.html

<form action="." method="POST">
    <input type="text" name="text2">
    <input type="submit" name="my-form" value="Send2">
</form>

【问题讨论】:

  • 下次使用按钮{}格式化代码。
  • 总是显示有问题的完整错误信息。文字bad request 没用。在调试模式下运行它 - app.run(debug=True) - 以在浏览器中获取更多信息。
  • 您确定它提交到正确的 URL 吗?让url_for 构建您的 URL 而不是硬编码它们通常是个好主意。

标签: python html redirect post flask


【解决方案1】:

"." 的网址不正确。

使用空字符串action="" 或删除action 将表单发送到相同的url

【讨论】:

  • 非常感谢伙计! ;)
【解决方案2】:
<form action="./questions" method="POST">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Send2">

通过编辑您的 index2.html action="./view" 这可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多