如何将从数据库获取的Python列表转换为Python字典以填充html页表?

问题描述 投票:0回答:1
import os
from sqlalchemy import create_engine, text


engine = create_engine(os.environ['DB_CONNECTION_STRING'])

def load_products_from_db():
  with engine.connect() as conn:
    result = conn.execute(text("select * from public.products"))
    products = []
    for row in result.all():
     products.append(dict(row))
      print(products)
    return products

我想将从 postgresdb 表 products 获取的 python 列表转换为 python 字典,以便我可以将获取的数据填充到 products.html 页面中。

postgresql flask-sqlalchemy replit
1个回答
0
投票
import os
from sqlalchemy import create_engine, text


engine = create_engine(os.environ['DB_CONNECTION_STRING'])

#this method is running a SQL query to select all rows from a table called 
"products" 
#by iterating the index of rows in the table using range() and len()
def load_products_from_db():
  with engine.connect() as conn:
    result = conn.execute(text("select * from products"))
    rows = result.all()
    products = []
    # Iterating the index of rows in the table using range() and len()
    for i in range(len(rows)):
      val = rows[I]
      products.append(dict(zip(result.keys(), val, strict=False)))
    return products
© www.soinside.com 2019 - 2024. All rights reserved.