Files
sless/examples/POSTGRES/code/table-reader/table_reader.py
T

28 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 2026-03-18
# table_reader.py — HTTP-функция: читает строки из terraform_demo_table и возвращает JSON.
# Подключается к Postgres через env vars (те же что у sql-runner).
import os
import psycopg2
import psycopg2.extras
def list_rows(event):
# Возвращает все строки terraform_demo_table в порядке убывания created_at.
connection = psycopg2.connect(
host=os.environ["PGHOST"],
port=os.environ.get("PGPORT", "5432"),
dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"],
sslmode=os.environ.get("PGSSLMODE", "require"),
)
try:
cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(
"SELECT id, title, created_at::text FROM terraform_demo_table ORDER BY created_at DESC"
)
rows = [dict(row) for row in cursor.fetchall()]
return {"rows": rows, "count": len(rows)}
finally:
connection.close()