使用 Python、flask 和 SQLAlchemy 如何在 HTML 页面上打印数据库查询的结果?

use*_*663 3 python sqlalchemy flask flask-sqlalchemy

我有一个非常简单的查询(刚开始使用 SQLAlchemy),我知道它正在工作,因为它在终端中打印,但不在 HTML 页面上打印,这就是问题所在。

如下:

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import *
from models import db, Candidate, User, Template
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

some_engine = create_engine('databse_url')
Session = sessionmaker(bind=some_engine)
session = Session()

@application.route("/", methods=['GET', 'POST'])
def index():
    res = session.query(Template).all()
    for temp in res:
            print temp.spark_id
    return render_template('index.html')
Run Code Online (Sandbox Code Playgroud)

在终端中,打印了 2 个“spark_id”,但在 HTML 页面上我什么也没得到。

在 index.html 页面中,我有:

% if res %}
    {% for temp in res %}

        <p>{{ temp.spark_id }}</p>
        <p>{{ temp.created_at }}</p>

    {% endfor %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

出了什么问题?

dpo*_*ggi 6

您没有将查询结果传递给您的模板:

return render_template('index.html', res=res)
Run Code Online (Sandbox Code Playgroud)