【发布时间】:2022-12-14 02:48:22
【问题描述】:
我正在尝试在 flask 中显示链接到各自数据的表列表(从 mysql 数据库中提取)。我已经能够列出这些表,但是当我点击它们时我得到一个错误:“%b 需要一个类似字节的对象,或者一个实现的对象字节,而不是'dict'”
这是我的代码:
from flask import Flask, render_template, redirect, request, flash, jsonify
from flask_mysqldb import MySQL,MySQLdb
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = ''
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'forddb'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
mysql = MySQL(app)
@app.route('/')
def index():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SHOW TABLES')
parts = cur.fetchall()
return render_template('index.html', parts=parts)
@app.route('/tableinfo')
def tableinfo():
cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SHOW TABLES')
tables=cur.fetchall()
for table in tables:
cur.execute('SELECT * FROM %s', (table))
data = cur.fetchall()
return render_template('inspection.html', data=data)
if __name__ == "__main__":
app.run(debug=True)
我的 index.html 是:
{% extends 'base.html' %}
{% block content %}
<h1>{% block title %} Pick Part Number to Start Inspection {% endblock %}</h1>
{% for parts in parts %}
<a href="{{ url_for('tableinfo') }}">
<h2>{{ parts.Tables_in_forddb }}</h2>
</a>
<hr>
{% endfor %}
{% endblock %}
我是一般的烧瓶和编程新手,希望了解如何循环遍历 SQL 数据库中的表,然后将它们分配给同名的 href 链接,然后路由到该表数据。我什至不确定这是否是正确的方法,我们将不胜感激。
【问题讨论】: