feat: POSTGRES example — add pg-table-reader HTTP function
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
psycopg2-binary==2.9.9
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 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()
|
||||||
@@ -95,3 +95,38 @@ resource "sless_job" "postgres_table_init_job" {
|
|||||||
depends_on = [nubes_postgres_database.db]
|
depends_on = [nubes_postgres_database.db]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# HTTP-функция читает строки из terraform_demo_table и возвращает JSON.
|
||||||
|
# Использует те же credentials что и sql-runner.
|
||||||
|
# Доступна по URL: https://sless.kube5s.ru/fn/<namespace>/pg-table-reader
|
||||||
|
resource "sless_function" "postgres_table_reader" {
|
||||||
|
name = "pg-table-reader"
|
||||||
|
runtime = "python3.11"
|
||||||
|
entrypoint = "table_reader.list_rows"
|
||||||
|
memory_mb = 128
|
||||||
|
timeout_sec = 30
|
||||||
|
|
||||||
|
env_vars = {
|
||||||
|
PGHOST = local.pg_host
|
||||||
|
PGPORT = "5432"
|
||||||
|
PGDATABASE = local.pg_database
|
||||||
|
PGUSER = local.pg_username
|
||||||
|
PGPASSWORD = local.pg_password
|
||||||
|
PGSSLMODE = "require"
|
||||||
|
}
|
||||||
|
|
||||||
|
source_dir = "${path.module}/code/table-reader"
|
||||||
|
|
||||||
|
depends_on = [sless_job.postgres_table_init_job]
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "sless_trigger" "postgres_table_reader_http" {
|
||||||
|
name = "pg-table-reader-http"
|
||||||
|
type = "http"
|
||||||
|
function = sless_function.postgres_table_reader.name
|
||||||
|
enabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
output "table_reader_url" {
|
||||||
|
value = sless_trigger.postgres_table_reader_http.url
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user