如何使Submisson框与sql/sqlite和flask、python一起工作?

2024-04-19 09:33:54 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我正在为自己制作一个测试清单系统,在这里我手动提交每个项目,但我在提交时遇到了麻烦。我已经解决了所有的html和python问题,但是当尝试提交所有内容时,会出现一个错误,提示IntegrityError:notnull约束失败:posts.condition

这是我的密码:

App.py

from flask_cors import CORS
from models import create_post, get_posts

app = Flask(__name__)

CORS(app)

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

    if request.method == 'GET':
        pass 

    if request.method == 'POST':
        post = request.form.get('post')
        item = request.form.get('item')
        TimenDate = request.form.get('TimenDate')
        condition = request.form.get('condition')
        history = request.form.get('history')

        create_post(item,TimenDate, condition, history)


    posts = get_posts()
    
   
    

    return render_template('index.html', posts=posts)

if __name__ == '__main__':
    app.run(debug=True)

ABB.sql文件:

    create table posts (
        id integer primary key autoincrement,
        item text not null,
        TimenDate text not null,
        condition text not null,
        history text not null
);

models.py文件:

from os import path

ROOT = path.dirname(path.relpath((__file__)))

def create_post(item,TimenDate,condition, history):
    con = sql.connect(path.join(ROOT, 'database.db'))
    cur = con.cursor()
    cur.execute('insert into posts (item, TimenDate,condition, history) values( ?, ?, ?, ?)', (item, TimenDate, condition, history))
    con.commit()
    con.close()
 
def get_posts():
    con = sql.connect(path.join(ROOT, 'database.db'))
    cur = con.cursor()
    cur.execute('select * from posts')
    posts = cur.fetchall()
    return posts

我的html文件:

<!doctype html>
<html>
    <body>
        <form action='/' role='form' method='POST'>
            <input placeholder='Item' name='item'>
            <input placeholder='TimenDate' name='TimenDate'>
            <input placeholder='Condition' name='Condition'>
            <input placeholder='History' name='History'>
            <input type='submit' value='Submit'>
        </form>
        {% for post in posts %}
            <div>{{ item[1] + ': ' + TimenDate[3]+ ': ' +Condition[5]+ ': ' +History[6]}}</div>
        {% endfor %}
    </body>
</html>

最后是错误:

create_post(item,TimenDate, condition, history)

File "/Users/mylaptop/ABB/models.py", line 9, in create_post
Open an interactive python shell in this framecur.execute('insert into posts (item, TimenDate,condition, history) values( ?, ?, ?, ?)', (item, TimenDate, condition, history))

谢谢你们的反馈。我确信它与abb.sql文件和数据库有关,但我不知道它是什么以及为什么


1条回答
网友
1楼 · 发布于 2024-04-19 09:33:54

表单发布的内容与路由期望的内容之间存在多个大写冲突。比如说

<input placeholder='Condition' name='Condition'>

condition = request.form.get('condition')

相关问题 更多 >