繁体   English   中英

Python Flask-如何获取 sqlalchemy 中的数据库以显示用户输入的数据

[英]Python Flask- How do I get the databse in sqlalchemy to display user inputted data

我正在处理一个需要用户在此任务管理器中输入日期的项目。 但是,无论何时运行代码,列警报中的值都会显示为无。

编辑:有关此的一些额外信息,在附件中,您可以看到时间如何简单地返回为 None,我遵循了建议并结合了两个 Todo,因此两者都被执行,但是现在它只是简单地返回“有”的异常返回一个错误'。

import os
import sched
import time
from flask  import Flask, render_template, url_for, request , redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime


app=Flask(__name__)     

app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///anothertest.db' #relative path
db = SQLAlchemy(app)

class Table(db.Model):
    id = db.Column(db.Integer, primary_key=True)    #refrencing id of each entry
    content = db.Column(db.String(50), nullable=True)   #the content that holds
    date_created = db.Column(db.DateTime, default=datetime.utcnow)  #print the date it was made
    alarm = db.Column(db.DateTime)    #stores the alarm

    def __repr__(self):
        return '<Task %r>' % self.id    #every new task made returns its own id
@app.route('/',methods=['POST','GET'])      #adding two methods posting and getting
def index():
    if request.method == 'POST':    #submitting form
        task_content = request.form['content'] #create new task from user input
        alarm_content = request.form['alarm']
        new_task = Table(content=task_content , alarm=alarm_content) #have the contents = input)

        try:
            db.session.add(new_task) #add to database
            db.session.commit()
            return redirect('/') #redirect to input page

        except:
            return 'There was an error'
    else:
        tasks = Table.query.order_by(Table.date_created).all() #showing all contents on site
        return render_template('index.html',tasks=tasks)    #user viewing the page

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

    try:
        db.session.delete(task_to_delete)
        db.session.commit()
        return redirect('/')

    except:
        return 'There was a problem'

if __name__ =="__main__":   
    app.run(debug=True)     #debugging true so errors are displayed

这是 HTML 部分

{%extends 'base.html' %}

{% block head %}
<title>Task Master</title>
{%endblock%}


{% block body %}
<div class="content">
    <h1 style = "text-align:center">Alexa</h1>

    <table border="1" align="center">
        <tr>
            <th>Task</th>
            <th>Created On</th>
            <th>Alarm Set For</th>
            <th>Actions</th>
        </tr>
        {% for task in tasks%} <!-- grab all tasks variables in the template-->
            <tr>
                <td>{{task.content}}</td> <!-- returns the contents of each task-->
                <td>{{task.date_created.date()}}</td>
                <td>{{task.alarm}}</td>
                <td>
                    <a href="/delete/{{task.id}}">Delete</a>
                    <br>
                </td>
            </tr>
        {% endfor %}
    </table>

<div>
    <form style="text-align: center;" id="ref" action="/" method='POST'>
        <br> 
    <input placeholder="Description of alarm" name="content" id="content">
    <input type="datetime-local" name="alarm" id="alarm">
    <input type="submit" value="Submit" name="submit"></form>
</div>
</form>
</div>
{%endblock%}

在这一行

new_task = Todo(content=task_content)

您正在创建Todo object 但仅设置content属性。

后来在这条线上

new_alarm = Todo(alarm=alarm_content)

您正在创建具有alarm属性的新Todo object。

但是,在try/catch块中,您只添加了只有content属性的new_task object。 new_alarm object 永远不会插入到数据库中。

我不确定您为什么要创建 2 个具有不同属性的Todo对象。 无论如何,我认为您应该只创建一个具有您要设置的所有属性的Todo object。 一个 object 将作为一行插入到数据库中。

所以,

new_todo = Todo(content="<content for the todo>", alarm="<alarm time and date>")

然后将new_todo插入数据库。

对于您问题的第二部分,请理解每个 URL 端点由一个 function 解决。

编辑:错误是由于alarm日期时间未正确处理。 您需要将alarm_content转换为 python datetime时间 object 才能将其存储到数据库中。 这是你可以做到的。

alarm_content = request.form['alarm']
alarm_tmp = alarm_content.replace('T', '-').replace(':', '-').split('-')
alarm_tmp = [int(v) for v in alarm_tmp]
alarm_datetime = datetime.datetime(*alarm_tmp)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM