Python-在HTML表格中显示查询结果

时间:2018-12-31 17:15:26

标签: python html sql-server

因此,我在Python中有以下Web应用程序,该应用程序应从MSSQL中的自定义表返回有关学生的信息(ID,姓名,姓氏):

from flask import Flask, render_template, redirect, url_for, request

from student import Student, students


app = Flask(__name__)


@app.route("/", methods=["GET", "POST"])
def students_page():
    if request.method == "POST":
        new_student_id = request.form.get("student-id", "")
        new_student_name = request.form.get("name", "")
        new_student_last_name = request.form.get("last-name", "")

        new_student = Student(name=new_student_name, last_name=new_student_last_name, student_id=new_student_id)
        students.append(new_student)

        return redirect(url_for("students_page"))

    return render_template("index.html", students=students)


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


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

这是我的Student班:

import pyodbc

students = []

conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=localhost;"
                      "Database=ERPBasic;"
                      "Trusted_Connection=yes;")

sql = '''SELECT Student_id, Name, Last_name FROM MyT'''
cursor = conn.cursor().execute(sql)

for row in cursor.fetchall():
    students.append(row)


class Student:

    school_name = "Springfield Elementary"

    def __init__(self, name, last_name, student_id):
        self.name = name
        self.last_name = last_name
        self.student_id = student_id
        students.append(self)

    def __str__(self):
        return "Student " + self.name

    def get_name_capitalize(self):
        return self.name.capitalize()

    def get_school_name(self):
        return self.school_name

以某种方式,当我在本地主机上运行Web应用程序时,该表不显示表中的查询结果,而仅显示4(四)个空行,我想显示查询的结果,如下所示:

[(1, 'Clarissa', 'Simpson'), (2, 'Gil', 'Kennedy'), (3, 'Owen', 'Willson'), (4, 'Sylvia', 'Burge')]

这是我的HTML桌子:

   <div class="page-header">
        <h1>All Students</h1>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>Student ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                {% for student in students %}
                <tr>
                    <td>{{ student.student_id }}</td>
                    <td>{{ student.name }}</td>
                    <td>{{ student.last_name }}</td>
                    <td>
                        <button class="btn btn-primary btn-sm">Edit</button>
                        <button class="btn btn-danger btn-sm">Delete</button>
                    </td>
                </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>

我在这里想念什么?谢谢

0 个答案:

没有答案