python - 如何从 sqlalchemy 获取元数据以在 jinja 中显示为表格?

标签 python flask sqlalchemy jinja2 flask-sqlalchemy

我在 postgres 和 mysql 中有一些数据库。我希望用户通过提供凭据来连接到数据库,然后在他正在查看的 html 上显示表的元数据(作为表)。

这是相关代码。

meta = MetaData()
meta.reflect(bind=eng)

return str(meta.tables)

这将返回 <class 'sqlalchemy.util._collections.immutabledict'> 类型的以下内容

immutabledict({'categories': Table('categories', MetaData(bind=None), Column('category', INTEGER(), table=, primary_key=True, nullable=False, server_default=DefaultClause(, for_update=False)), Column('categoryname', VARCHAR(length=50), table=, nullable=False), schema=None), 'inventory': Table('inventory', MetaData(bind=None), Column('prod_id', INTEGER(), table=, primary_key=True, nullable=False), Column('quan_in_stock', INTEGER(), table=, nullable=False), Column('sales', INTEGER(), table=, nullable=False), schema=None), 'products': Table('products', MetaData(bind=None), Column('prod_id', INTEGER(), table=, primary_key=True, nullable=False, server_default=DefaultClause(, for_update=False)), Column('category', INTEGER(), table=, nullable=False), Column('title', VARCHAR(length=50), table=, nullable=False), Column('actor', VARCHAR(length=50), table=, nullable=False), Column('price', NUMERIC(precision=12, scale=2), table=, nullable=False), Column('special', SMALLINT(), table=), Column('common_prod_id', INTEGER(), table=, nullable=False), schema=None), 'reorder': Table('reorder', MetaData(bind=None), Column('prod_id', INTEGER(), table=, nullable=False), Column('date_low', DATE(), table=, nullable=False), Column('quan_low', INTEGER(), table=, nullable=False), Column('date_reordered', DATE(), table=), Column('quan_reordered', INTEGER(), table=), Column('date_expected', DATE(), table=), schema=None), 'cust_hist': Table('cust_hist', MetaData(bind=None), Column('customerid', INTEGER(), ForeignKey('customers.customerid'), table=, nullable=False), Column('orderid', INTEGER(), table=, nullable=False), Column('prod_id', INTEGER(), table=, nullable=False), schema=None), 'customers': Table('customers', MetaData(bind=None), Column('customerid', INTEGER(), table=, primary_key=True, nullable=False, server_default=DefaultClause(, for_update=False)), Column('firstname', VARCHAR(length=50), table=, nullable=False), Column('lastname', VARCHAR(length=50), table=, nullable=False), Column('address1', VARCHAR(length=50), table=, nullable=False), Column('address2', VARCHAR(length=50), table=), Column('city', VARCHAR(length=50), table=, nullable=False), Column('state', VARCHAR(length=50), table=), Column('zip', INTEGER(), table=), Column('country', VARCHAR(length=50), table=, nullable=False), Column('region', SMALLINT(), table=, nullable=False), Column('email', VARCHAR(length=50), table=), Column('phone', VARCHAR(length=50), table=), Column('creditcardtype', INTEGER(), table=, nullable=False), Column('creditcard', VARCHAR(length=50), table=, nullable=False), Column('creditcardexpiration', VARCHAR(length=50), table=, nullable=False), Column('username', VARCHAR(length=50), table=, nullable=False), Column('password', VARCHAR(length=50), table=, nullable=False), Column('age', SMALLINT(), table=), Column('income', INTEGER(), table=), Column('gender', VARCHAR(length=1), table=), schema=None), 'orders': Table('orders', MetaData(bind=None), Column('orderid', INTEGER(), table=, primary_key=True, nullable=False, server_default=DefaultClause(, for_update=False)), Column('orderdate', DATE(), table=, nullable=False), Column('customerid', INTEGER(), ForeignKey('customers.customerid'), table=), Column('netamount', NUMERIC(precision=12, scale=2), table=, nullable=False), Column('tax', NUMERIC(precision=12, scale=2), table=, nullable=False), Column('totalamount', NUMERIC(precision=12, scale=2), table=, nullable=False), schema=None), 'orderlines': Table('orderlines', MetaData(bind=None), Column('orderlineid', INTEGER(), table=, nullable=False), Column('orderid', INTEGER(), ForeignKey('orders.orderid'), table=, nullable=False), Column('prod_id', INTEGER(), table=, nullable=False), Column('quantity', SMALLINT(), table=, nullable=False), Column('orderdate', DATE(), table=, nullable=False), schema=None)})

我在 jinja 模板中尝试了一个 for 循环,但它显示 sqlalchemy 'table' object is not iterable

如何从数据库获取元数据以在 html 中显示为表格?

最佳答案

inspector类有助于访问元数据。

from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
engine = create_engine('...')
insp = reflection.Inspector.from_engine(engine)
print(insp.get_table_names())

其他可用的方法有

get_check_constraints
get_columns
get_foreign_keys
get_indexes
get_pk_constraint
get_schema_names

有关说明和更多方法,请参阅文档。然后,您可以将变量传输到 jinja 模板并相应地打印它。

这就是我为我的工作示例所做的。

tablenames = insp.get_table_names()
return render_template('tables.html', inspector=insp, table=tablenames)

金贾:

<table>
    <tr>
        <th>table</th>
        <th>name</th>
        <th>type</th>
        <th>nullable</th>
        <th>default</th>
        <th>autoincrement</th>
        <th>comment</th>
    </tr>
    {% for table in table %}
        {% for col in inspector.get_columns(table_name=table) %}
            <tr>
            <td>{{ table }}</td>
            {% for val in col.values() %}
                <td>{{ val }}</td>
            {% endfor %}
            </tr>
        {% endfor %}
    {% endfor %}
</table>

关于python - 如何从 sqlalchemy 获取元数据以在 jinja 中显示为表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53667673/

相关文章:

python - 如何将多个模板传递给 flask.render_template()

react-native - Cookie 未正确存储在 ios 模拟器中

python - SQLalchemy from_statement() 找不到列

python - 删除重复的 Pandas 和 SQLAlchemy

python - 删除查询集中的重复项

python - 有没有一种Python式的方法将基于范围的分段函数分组为单个函数?

python - ServerNotFoundError : Unable to find the server at accounts. google.com

python - 为什么 `requests`要用 `with`语句呢?

python TypeError 使用 timedelta 添加时间

python - 如何使用sqlalchemy的hybrid_property查询多个字段?