Python烧瓶形式

时间:2020-06-19 19:18:11

标签: python forms sqlite flask

也许您可以帮助我解决以下代码/问题。我想用烧瓶和sqlite编写一个小工具来记录我的工作时间。尽管我以前能够连接到数据库,但似乎在连接数据库时遇到了麻烦。这段代码:

from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///time-clock.db'
db = SQLAlchemy(app)

class Project_Work(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    project = db.Column(db.String(200), unique=False, nullable=False)   
    content = db.Column(db.String(200), unique=False, nullable=False)   
    date_start = db.Column(db.DateTime, unique=False, nullable=False)   
    date_end = db.Column(db.DateTime, unique=False, nullable=False)     
    time = db.Column(db.Float, unique=False, nullable=False)            

    def __repr__(self):
        return '<Task %r>' % self.id

@app.route('/', methods=['POST', 'GET'])
def index():
    tasks = Project_Work.query
    return render_template('index.html', tasks=tasks)


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

    if request.method == 'POST':
        project = request.form['project']
        content = request.form['content']

        start = datetime.datetime.strptime(request.form['date_end'], '%Y-%m-%d %H:%M:%S')
        end = datetime.datetime.strptime(request.form['date_end'], '%Y-%m-%d %H:%M:%S')

        new_task = Project_Work(project=project, content=content, date_start = start, date_end = end, time = 8)

        try:
            db.session.add(new_task)
            db.session.commit()
            return redirect('/')

        except:
            return 'There was an issue adding your task'

    else:
        tasks = Project_Work.query
        return render_template('form.html', tasks=tasks)

@app.route('/delete/<int:id>')
def delete(id):
    task_to_delete = Project_Work.query.get_or_404(id)

    try:
        db.session.delete(task_to_delete)
        db.session.commit()
        return redirect('/')
    except:
        return 'There was a problem deleting that task'

#Following function updates existings entries in the database by using the entry-id.

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    task = Project_Work.query.get_or_404(id)

    if request.method == 'POST':
        task.content = request.form['content']

        try:
            db.session.commit()
            return redirect('/')
        except:
            return 'There was an issue updating your task'

    else:
        return render_template('update.html', task=task)

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

我能够从python终端创建数据库。当我将数据手动放入数据库中时,我能够从数据库中读取所有内容。如果我尝试将数据从表单写入数据库,则该工具仅重定向到主页,而没有将数据写入数据库。似乎该工具未连接到数据库。我没有收到任何错误消息。

您有任何想法我在做什么错吗?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试以此更新路线时更新数据库内容

Project_Work.query.filter_by(id=id).update(
    dict(
        content=request.form["content"]
    )
)
db.session.commit()

代替此

task.content = request.form['content']

另外,最好检查内容是否为空