如何获取Flask中的最后一个条目

2024-09-30 20:24:38 发布

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

我正在尝试从quickquizlist.html输入中获取最后一个条目,并在test.html上获取它。我尝试了app.py,但没有成功,也尝试了html页面本身,但没有成功。我不是专家,但我认为我的数据保存在会话中,而不是像我所认为的那样保存在sqlalchemy中。这不是问题所在,我只想从html页面获取最后一个条目,并将其放在另一个html页面上

该场景是,当用户填写文本输入时,所有数据(因为用户可以多次输入)将作为表格打印在result.html上。我只想在test.html上打印最后一个条目


这是我的app.py

from flask import Flask, render_template, request, flash, url_for, redirect, session
from flask_sqlalchemy import SQLAlchemy
import ctypes
import sqlite3
from sqlalchemy import sql, create_engine, select, MetaData, Table
# engine = create_engine("dburl://user:pass@database/schema")
# metadata = MetaData(bind=None)
# table = Table('table_name', metadata, autoload = True, autoload_with = engine)
# stmt = select([table]).where(table.columns.column_name == 'filter')
#
# connection = engine.connect()
# results = connection.execute(stmt).fetchall()


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/AFEER/projects/hello_flask/database.db'
app.config['SECRET_KEY'] = "random string"

db = SQLAlchemy(app)
db.app = app
# SQLAlchemy.drop_all()
#Base.metadata.drop_all(engine)   # all tables are deleted
# Inserts records into a mapping table
#db.session.add (model object)
# delete records from a table
#db.session.delete (model object)
# retrieves all records (corresponding to SELECT queries) from the table.
#model.query.all ()


#questions table
class quickQuizQuestions(db.Model):
    def __init__(self, TFquestion, TFanswer, MCQquestion, MCQanswer):
        self.TFquestion = TFquestion
        self.TFanswer = TFanswer
        self.MCQquestion = MCQquestion
        self.MCQanswer = MCQanswer
        # obj = quickQuizQuestions()
        # db.session.add(obj)
        # db.session.commit()
        # obj = quickQuizQuestions()
        # db.session.add(obj)
        # db.session.commit()
    id = db.Column('question_id', db.Integer, primary_key=True)
    TFquestion = db.Column(db.String(900))
    TFanswer = db.Column(db.String(1))
    MCQquestion = db.Column(db.String(900))
    MCQanswer = db.Column(db.String(1))

#students answers table
class studentAnswer(db.Model):
    def __init__(self, student_id, student_name, student_answer, postedQuestion):
        self.student_id = student_id
        self.student_name = student_name
        self.student_answer = student_answer
        self.postedQuestion = postedQuestion
        # obj = studentAnswer()
        # db.session.add(obj)
        # db.session.commit()
    id = db.Column(db.Integer, primary_key=True)
    # student_id = password
    student_id = db.Column(db.Integer)
    student_name = db.Column(db.String(50))
    student_answer = db.Column(db.String(1))
    postedQuestion = db.Column(db.String(900))

    #to render The record set of the student table is sent as a parameter to the HTML template.
    # The server-side code in the template renders the record as an HTML table
@app.route('/result')
def result():
        return render_template('result.html', quickQuizQuestions=quickQuizQuestions.query.all())


@app.route('/')
def Welcome():
    return render_template('Welcome.html')

@app.route('/InstructorLogin')
def InstructorLogin():
    return render_template('InstructorLogin.html')

@app.route('/StudentLogin')
def StudentLogin():
    return render_template('StudentLogin.html')

@app.route('/quickQuizList', methods=['GET', 'POST'])
def quickQuizList():
    if request.method == 'POST':
        if request.form['TFtxtarea'] or request.form['MCQtxtarea']:
            question = quickQuizQuestions(request.form['TFtxtarea'], request.form['TFanswer'], request.form['MCQtxtarea'], request.form['MCQanswer'])
            db.session.add(question)
            db.session.commit()
            flash('Record was successfully added')
            return render_template("result.html")
        else:
            flash('Please enter all the fields', 'error')

    return render_template("quickQuizList.html")

@app.route('/StudentPage')
def StudentPage():
    return render_template('StudentPage.html')

@app.route('/test')
def test():
        return render_template('test.html', quickQuizQuestions=db.session.query().select_from(quickQuizQuestions).order_by(quickQuizQuestions.id.desc()).first())
        # obj = session.query(quickQuizQuestions).order_by(quickQuizQuestions.id.desc()).first()
        # flash(obj)
        # return render_template('test.html')

    # return render_template('test.html', quickQuizQuestions=quickQuizQuestions.query.all())


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

这是我的quickquizlist.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tools</title>
<style>

.header {
  overflow: hidden;
  background-color: #3F3B72;
  padding: 20px 10px;
}
.header-right {
  float: right;
}
.header a.logo {
  font-size: 25px;
  font-weight: bold;

}
.header a {
  float: left;
  color: white;
  text-align: center;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  line-height: 25px;
  border-radius: 4px;
}
#buttonClos{
box-shadow: 0px 1px 0px 0px #f0f7fa;
    background:linear-gradient(to bottom, #33bdef 5%, #019ad2 100%);
    background-color:#33bdef;
    border-radius:6px;
    border:1px solid #057fd0;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Verdana;
    font-size:15px;
    font-weight:bold;
    padding:7px 18px;
    text-decoration:none;
    text-shadow:0px 0px 0px #5b6178;display:inline-block;

}

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  background-color: #FFFAFA;
}

.form{padding:20px;
font-size:20px;
}
</style>
    <script>
function quickQuiz() {

        var questionType = document.getElementById("questionType").value;

<!--        TF elements-->
        var TFtxtarea = document.getElementById("TFtxtarea");
        var label1 = document.getElementById("label1");
        var TFanswer = document.getElementById("TFanswer");
        var TFsubmit = document.getElementById("TFsubmit");

<!--        MCQ elements-->
        var MCQtxtarea = document.getElementById("MCQtxtarea");
        var a = document.getElementById("a");
        var b = document.getElementById("b");
        var c = document.getElementById("c");
        var txta = document.getElementById("txta");
        var txtb = document.getElementById("txtb");
        var txtc = document.getElementById("txtc");
        var MCQsubmit = document.getElementById("MCQsubmit");
        var label2 = document.getElementById("label2");
        var MCQanswer = document.getElementById("MCQanswer");

        if(questionType == "TF" || questionType == "tf")
        {
            TFtxtarea.style.display="block";
            label1.style.display="block";
            TFanswer.style.display="block";
            TFsubmit.style.display="block";

            MCQtxtarea.style.display="none";
            a.style.display="none";
            b.style.display="none";
            c.style.display="none";
            txta.style.display="none";
            txtb.style.display="none";
            txtc.style.display="none";
            MCQsubmit.style.display="none";
            label2.style.display="none";
            MCQanswer.style.display="none";
        }

        if(questionType == "MCQ" || questionType == "mcq")
        {
            MCQtxtarea.style.display="block";
            a.style.display="block";
            b.style.display="block";
            c.style.display="block";
            txta.style.display="block";
            txtb.style.display="block";
            txtc.style.display="block";
            MCQsubmit.style.display="block";
            label2.style.display="block";
            MCQanswer.style.display="block";

            TFtxtarea.style.display="none";
            label1.style.display="none";
            TFanswer.style.display="none";
            TFsubmit.style.display="none";
        }
  }
</script>
</head>
{%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {{ message }}
         </div>
      {%- endfor %}
<div class="header">
    <a class="logo">QuickQuiz</a>

</div>
<form action = "{{ request.path }}" method = "POST">
<div  class="form">
   <p> Enter the question type (TF/MCQ):</p>
    <input type="text" id="questionType" placeholder="TF or MCQ:">
    <br><br>
<label style="border:inset" id="submitQuestionType" onclick="quickQuiz()"> Submit</label>
    <br><br>

    <textarea name="TFtxtarea" id="TFtxtarea" style="display:none" placeholder="Type your TF question here"></textarea>
    <br><br>
    <label style="display:none" id="label1">Enter the correct answer:</label>
    <input style="display:none" type="text" id="TFanswer" name="TFanswer">
    <br>
    <input style="display:none" id="TFsubmit" type = "submit" value = "Submit & Post" />

    <textarea name="MCQtxtarea" id="MCQtxtarea" style="display:none" placeholder="Type your MCQ question here"></textarea>
    <br>
    <label id="a" style="display:none">Option A</label>
    <input type="text" id="txta" style="display:none"> <br>
    <label id="b" style="display:none">Option B</label>
    <input type="text" id="txtb" style="display:none"> <br>
    <label id="c" style="display:none">Option C</label>
    <input type="text" id="txtc" style="display:none">

    <br>
    <label id="label2" style="display:none">Enter the correct answer</label>
    <input type="text" id="MCQanswer" name="MCQanswer" style="display:none">
    <br>
    <input type="submit" id="MCQsubmit" style="display:none" value="Submit & Post">

</div>
</form>
</body>
</html>

这是result.html

<!DOCTYPE html>
<html lang = "en">
   <head>
      <script src="https://cdn.jsdelivr.net/gh/linways/table-to-excel@v1.0.4/dist/tableToExcel.js"></script>
<script>
function exportReportToExcel() {
  let table = document.getElementsByTagName("table");
  TableToExcel.convert(table[0], {
    name: `Questions & Answers.xlsx`,
    sheet: {
      name: 'Sheet 1'
    }
  });
}

</script>
   </head>
   <body style="font-family: Arial, Helvetica, sans-serif;
  background-color: #FFFAFA;">
<div   style="width:800px; margin:0 auto;">
      <h3>
         <a style="color:#14568B;" href = "{{ url_for('result') }}"> Click to Show Table of Questions and Answers</a>
      </h3>

      <hr/>
      {%- for message in get_flashed_messages() %}
         {{ message }}
      {%- endfor %}

      <h3> (<a style="color:#14568B;" href = "{{ url_for('quickQuizList') }}">Click to Add Quick Quiz Question
         </a>)</h3>

      <table style="border: 1px solid black;">
         <thead>
            <tr width="380" style="border: 20px solid black ;">
               <th width="80" style="border: 1px solid black ;">TF Question</th>
               <th width="80" style="border: 1px solid black ;">TF Answer</th>
               <th width="80" style="border: 1px solid black ;">MCQ Question</th>
               <th width="80" style="border: 1px solid black ;">MCQ Answer</th>
            </tr>
         </thead>

         <tbody>
            {% for question in quickQuizQuestions %}
               <tr style="border: 1px solid black;">
                  <td style="border: 1px solid black;">{{ question.TFquestion }}</td>
                  <td style="border: 1px solid black;">{{ question.TFanswer }}</td>
                  <td style="border: 1px solid black;">{{ question.MCQquestion }}</td>
                  <td style="border: 1px solid black;">{{ question.MCQanswer }}</td>
               </tr>
            {% endfor %}
         </tbody>
      </table>
<br>
      <br>
<button id="btnExport" onclick="exportReportToExcel(this)">Download Report</button>
   </div>
   </body>
</html>

这是test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<h1>Answer The Following Question</h1>
<form method="POST">
<label id="questionLabel" ></label>


    <p>
<!--        <label>{{ quickQuizQuestions|length }} HERE!</label>-->
        <label>
<!--              {% for question in quickQuizQuestions %}-->
<!--              {% if loop.lenght == quickQuizQuestions|length %}-->

<!--              {% endif %}-->
<!--            {% endfor %}-->
<!--                        {{quickQuizQuestions|string}} HERE-->
                test
        </label>
    </p>

</form>
</body>
</html>

Tags: noneidappdbstylevarhtmldisplay
1条回答
网友
1楼 · 发布于 2024-09-30 20:24:38

您正在使用quickQuizQuestions.query.all()从数据库检索所有对象

您只想检索一个对象;你的最后一个条目。如果您的问题id不增加,您可以使用:

quickQuizQuestions.query.order_by(-quickQuizQuestions.id).limit(1).all()

quickQuizQuestions.query.order_by(-quickQuizQuestions.id).first()

直接检索它

相关问题 更多 >