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 页面中。
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