【问题标题】:Linking tables in MySQL to their respective data with Flask使用 Flask 将 MySQL 中的表链接到它们各自的数据
【发布时间】: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 链接,然后路由到该表数据。我什至不确定这是否是正确的方法,我们将不胜感激。

【问题讨论】:

    标签: python mysql flask


    【解决方案1】:

    终于想通了将“tableinfo”路由更改为:

    @app.route('/tableinfo/<id>')
    def tableinfo(id):
        cur = mysql.connection.cursor()
        cur.execute('SHOW TABLES')
        tables=cur.fetchall()
        for table in tables:
            cur.execute(f"SELECT * FROM {id}")
            table = cur.fetchall()
            return render_template('inspection.html', table=table)
    

    和 index.html 到:

    {% extends 'base.html' %}
    {% block content %}
    
    <h1>{% block title %} Pick Part Number to Start Inspection {% endblock %}</h1>
    
        {% for tables in tables %}
            <hr>
            <a href="{{ url_for('tableinfo', id=tables.Tables_in_forddb) }}">
                <h2>{{ tables.Tables_in_forddb }}</h2>
            </a>
            <hr>
        {% endfor %}
    
    {% endblock %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2015-04-07
      • 2020-07-07
      • 1970-01-01
      • 2017-07-23
      相关资源
      最近更新 更多