【问题标题】:Why is my MySQL data not displaying to html template?为什么我的 MySQL 数据没有显示到 html 模板?
【发布时间】:2019-11-29 07:03:07
【问题描述】:

我一直在尝试显示来自 MySQL 数据库的数据,但没有任何效果。代码如下:

@app.route('/',methods=['GET','POST'])
def index():
 if request.method == "POST":
    food = request.form['food']
    cur = mysql.connection.cursor()
    data = cur.execute("SELECT * FROM recipies WHERE title = %s",[food])
    if data > 0 :
       results = cur.fetchall()
       return render_template('results.html',results=results)

和 html

% extends "base.html" %}
{% block content %}

{% for result in results %}
        <table>
                <td>{{ result }}</td>
        </table>

{% endfor %}


{% endblock %}

当我运行它时,它给出了一个错误“TypeError:视图函数没有返回一个有效的响应。该函数要么返回 None,要么在没有返回语句的情况下结束。” 我不知道该怎么办。

【问题讨论】:

  • 你对 if 有 else 吗?另外,我猜您检查数据是否返回的方式不正确。
  • 我尝试添加一个 else 但结果是一样的。

标签: python mysql flask


【解决方案1】:

对您的函数进行以下更改:

@app.route('/',methods=['GET','POST'])
def index():
    if request.method == "POST":
        food = request.form['food']
        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM recipies WHERE title = %s",[food])
        results = []
        if not cur.rowcount:
            print "No results found"
        else:
            results = cur.fetchall()
        return render_template('results.html',results=results)

【讨论】:

  • 我进行了更改,但没有任何改进。
猜你喜欢
  • 2020-11-08
  • 1970-01-01
  • 2022-10-16
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多