【发布时间】: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