首页 > 解决方案 > POST 方法不适用于 Flask 应用程序 - 错误 404

问题描述

我正在尝试构建一个简单的 Flask 应用程序,它将运行一个连接到 Postgres 数据库的 Web 应用程序。

但是,当我运行代码并单击提交按钮时,POST 方法不起作用,因此它确实返回指定的 {{url_for('success]}}。我尝试添加和删除几个组件。我有方法= ['GET', 'POST'] 已经。

应用程序.py:

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy

from sqlalchemy.sql import func

app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:postgres@localhost/Jeopardy'
db=SQLAlchemy(app)

class Data(db.Model):
    __tablename__="allc"
    number = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String())
    question = db.Column(db.String())
    answer = db.Column(db.String())


    def __init__(self,number,category,question,answer):
        self.number = number
        self.category = category
        self.question = question
        self.answer = answer
        

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

@app.route("/success", methods=['POST','GET'])
def success():
    if request.method=='POST':
        category=request.form['category']
        question=request.form['question']
        answer=request.form['answer']
        number=request.form['number']
    
        print(email, height)
        if db.session.query(Data).filter(Data.number == number).count()== 0:
            data=Data(number,category,question,answer)
            db.session.add(data)
            db.session.commit()
            
            return render_template("success.html")
    
if __name__ == '__main__':
    app.debug=True
    app.run()

索引.html:

<html lang="en">
<title>Jeopardy</title>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device=width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="../static/style.css" rel="stylesheet"  >
</head>
<body>
    <div class="="container">
        <img src="../static/logo.png" alt="Jeopardy" class ="logo">
        <!-- @todo - message-->
        <form action = "s{{url_for('success')}}" methods="POST">
            <div class =  " form-group">
            <h3>Jeopardy Question</h3>
            <input
                    type = "number"
                    name = "Index"
                    placeholder= "Type number" />
                <input
                    type = "text"
                    name = "Question"
                    placeholder= "Type the Jeopardy question here" />
                    <input
                        type = "text"
                        name = "Answer"
                        placeholder= "Type the Jeopardy Answer here"/>
                <button type = "submit"> Submit</button>
        </form>
    </div>
</body>
</html>

在运行代码时,我的应用程序成功呈现,但在提交数字时,服务器没有注册输入。单独加载成功页面时,它会加载。在终端中,我看到:"POST /success HTTP/1.1" 404 -

标签: pythonhtmlpostgresqlflaskflask-sqlalchemy

解决方案


您的 html 中有错字

它应该是method="post"而不是methods="post"

编辑:

中的另一个错字

action = "s{{url_for('success')}}"

去掉“s”


推荐阅读