【问题标题】:Can someone help me resolve this issue for Flask有人可以帮我解决 Flask 的这个问题吗
【发布时间】:2020-06-05 11:41:03
【问题描述】:

我尝试了一项从互联网上获取的任务,用于显示从烧瓶到 hmtl 表单的数据。 但是这里的问题是我遇到了两个错误:- 1)flask中渲染的html文件没有找到。 2)SQL表和列没有解析。

我已尝试通过互联网通过多种解决方案解决此问题。 我在 Pycharm 上试了一下,使用 MariaDB Connector,测试连接成功。 有人可以帮我解决吗?

烧瓶代码如下:-

from flask import Flask, render_template, request
from flaskext.mysql import MySQL

app = Flask(__name__)
# Database connection info
app.config['MYSQL_DATABASE_USER'] = 'root'

app.config['MYSQL_DATABASE_PASSWORD'] = ''

app.config['MYSQL_DATABASE_DB'] = 'LibraryDB'

app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql = MySQL()

mysql.init_app(app)

conn = mysql.connect()

cursor = conn.cursor()

@app.route('/search', methods=['GET', 'POST'])

def search():

    if request.method == "POST":

        book = request.form['book']

        # search by author or book

        cursor.execute("SELECT name, author from book WHERE name LIKE %s OR author LIKE %s", (book,book))

        conn.commit()

        data = cursor.fetchall()

        # all in the search box will return all the tuples

        if len(data) == 0 and book == 'all':

            cursor.execute("SELECT name, author from Book")

            conn.commit()

            data = cursor.fetchall()

        return render_template('search.html', data=data)

    return render_template('search.html')

if __name__ == '__main__':

    app.debug = True

    app.run()

我的 HTML 代码如下:-

<!DOCTYPE html>
<html lang="utf-8">
    <head>
        <link rel="stylesheet" href="../static/index.css" type="text/css">
        <title>Search</title>
    </head>
    <body>
        <h1 style="text-align: center;">Library</h1>
        <form class="example" method="post" action=""
         style="margin:auto;max-width:600px">
            <label>
                <input type="text" placeholder="Search by author or book, or all to see all the data" name="book">
            </label>
            <button type="submit">Search<i class="fa fa-search"></i>
            </button>
        </form>
        <p></p>
        <div style="text-align: center;">
        {% for item in data %}
            <tr>
                <td> {{item[0]}} by {{item[1]}}</td>
            </tr>
        {% endfor %}
        </div>
    </body>
</html>

CSS 没问题,所以我们不要打扰它

【问题讨论】:

  • 您需要指定确切的错误,例如发生错误的行或共享屏幕截图

标签: python html mysql database flask


【解决方案1】:

您是否检查过数据是否被解析到您的查询中,并且是否从表中获取结果?您可以使用以下代码进行检查:

print(cursor._executed)

在 cursor.execute() 之后

对于错误号 1: 我会说请验证 HTML 文件的名称。

p.s 不需要使用conn.commit(),因为建议仅在创建记录、更新记录或从表中删除记录时使用,因此您可以继续删除该部分。

让我知道这是否对您有帮助。

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多